text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Presses left control or command button depending on OS, clicks and then releases control or command key.
<END_TASK>
<USER_TASK:>
Description:
def multi_click(self, locator, params=None, timeout=None):
"""
Presses left control or command button depending on OS, clicks and then releases control or command key.
:param locator: locator tuple or WebElement instance
:param params: (optional) locator parameters
:param timeout: (optional) time to wait for element
:return: None
""" |
platform = self.execute_script('return navigator.platform')
multi_key = Keys.COMMAND if 'mac' in platform.lower() else Keys.LEFT_CONTROL
self._click(locator, params, timeout, multi_key) |
<SYSTEM_TASK:>
Clicks a web element and shift clicks another web element.
<END_TASK>
<USER_TASK:>
Description:
def shift_select(self, first_element, last_element):
"""
Clicks a web element and shift clicks another web element.
:param first_element: WebElement instance
:param last_element: WebElement instance
:return: None
""" |
self.click(first_element)
self.shift_click(last_element) |
<SYSTEM_TASK:>
Multi-select any number of elements.
<END_TASK>
<USER_TASK:>
Description:
def multi_select(self, elements_to_select):
"""
Multi-select any number of elements.
:param elements_to_select: list of WebElement instances
:return: None
""" |
# Click the first element
first_element = elements_to_select.pop()
self.click(first_element)
# Click the rest
for index, element in enumerate(elements_to_select, start=1):
self.multi_click(element) |
<SYSTEM_TASK:>
Select option from drop down widget using value.
<END_TASK>
<USER_TASK:>
Description:
def select_from_drop_down_by_value(self, locator, value, params=None):
"""
Select option from drop down widget using value.
:param locator: locator tuple or WebElement instance
:param value: string
:param params: (optional) locator parameters
:return: None
""" |
from selenium.webdriver.support.ui import Select
element = locator
if not isinstance(element, WebElement):
element = self.get_present_element(locator, params)
Select(element).select_by_value(value) |
<SYSTEM_TASK:>
Select option from drop down widget using text.
<END_TASK>
<USER_TASK:>
Description:
def select_from_drop_down_by_text(self, drop_down_locator, option_locator, option_text, params=None):
"""
Select option from drop down widget using text.
:param drop_down_locator: locator tuple (if any, params needs to be in place) or WebElement instance
:param option_locator: locator tuple (if any, params needs to be in place)
:param option_text: text to base option selection on
:param params: Dictionary containing dictionary of params
:return: None
""" |
# Open/activate drop down
self.click(drop_down_locator, params['drop_down'] if params else None)
# Get options
for option in self.get_present_elements(option_locator, params['option'] if params else None):
if self.get_text(option) == option_text:
self.click(option)
break |
<SYSTEM_TASK:>
Select option from drop down widget using locator.
<END_TASK>
<USER_TASK:>
Description:
def select_from_drop_down_by_locator(self, drop_down_locator, option_locator, params=None):
"""
Select option from drop down widget using locator.
:param drop_down_locator: locator tuple or WebElement instance
:param option_locator: locator tuple or WebElement instance
:param params: Dictionary containing dictionary of params
:return: None
""" |
# Open/activate drop down
self.click(drop_down_locator, params['drop_down'] if params else None)
# Click option in drop down
self.click(option_locator, params['option'] if params else None) |
<SYSTEM_TASK:>
Get attribute from element based on locator with optional parameters.
<END_TASK>
<USER_TASK:>
Description:
def get_attribute(self, locator, attribute, params=None, timeout=None, visible=False):
"""
Get attribute from element based on locator with optional parameters.
Calls get_element() with expected condition: visibility of element located
:param locator: locator tuple or WebElement instance
:param attribute: attribute to return
:param params: (optional) locator parameters
:param timeout: (optional) time to wait for text (default: None)
:param visible: should element be visible before getting text (default: False)
:return: element attribute
""" |
element = locator
if not isinstance(element, WebElement):
element = self.get_present_element(locator, params, timeout, visible)
try:
return element.get_attribute(attribute)
except AttributeError:
msg = "Element with attribute <{}> was never located!".format(attribute)
raise NoSuchElementException(msg) |
<SYSTEM_TASK:>
Get text or value from element based on locator with optional parameters.
<END_TASK>
<USER_TASK:>
Description:
def get_text(self, locator, params=None, timeout=None, visible=True):
"""
Get text or value from element based on locator with optional parameters.
:param locator: element identifier
:param params: (optional) locator parameters
:param timeout: (optional) time to wait for text (default: None)
:param visible: should element be visible before getting text (default: True)
:return: element text, value or empty string
""" |
element = locator
if not isinstance(element, WebElement):
element = self.get_present_element(locator, params, timeout, visible)
if element and element.text:
return element.text
else:
try:
return element.get_attribute('value')
except AttributeError:
return "" |
<SYSTEM_TASK:>
Enter text into a web element.
<END_TASK>
<USER_TASK:>
Description:
def enter_text(self, locator, text, with_click=True, with_clear=False, with_enter=False, params=None):
"""
Enter text into a web element.
:param locator: locator tuple or WebElement instance
:param text: text to input
:param with_click: clicks the input field
:param with_clear: clears the input field
:param with_enter: hits enter-key after text input
:param params: (optional) locator params
:return: None
""" |
element = locator
if not isinstance(element, WebElement):
element = self.get_visible_element(locator, params)
if with_click:
self.click(element)
actions = ActionChains(self.driver)
if 'explorer' in self.driver.name and "@" in str(text):
actions = BasePage.handle_at_sign_for_ie(text, actions)
else:
actions.send_keys_to_element(element, text)
if with_clear:
element.clear()
# Click to regain focus as clear does clear w/ blur by design -
# https://w3c.github.io/webdriver/webdriver-spec.html#element-clear
self.click(element)
if with_enter:
actions.send_keys(Keys.ENTER)
actions.perform() |
<SYSTEM_TASK:>
Various ways to erase text from web element.
<END_TASK>
<USER_TASK:>
Description:
def erase_text(self, locator, click=True, clear=False, backspace=0, params=None):
"""
Various ways to erase text from web element.
:param locator: locator tuple or WebElement instance
:param click: clicks the input field
:param clear: clears the input field
:param backspace: how many times to hit backspace
:param params: (optional) locator params
:return: None
""" |
element = locator
if not isinstance(element, WebElement):
element = self.get_visible_element(locator, params)
if click:
self.click(element)
if clear:
element.clear()
if backspace:
actions = ActionChains(self.driver)
for _ in range(backspace):
actions.send_keys(Keys.BACKSPACE)
actions.perform() |
<SYSTEM_TASK:>
Drag source element and drop at target element.
<END_TASK>
<USER_TASK:>
Description:
def drag_and_drop(self, source_element, target_element, params=None):
"""
Drag source element and drop at target element.
Note: Target can either be a WebElement or a list with x- and y-coordinates (integers)
:param source_element: WebElement instance
:param target_element: WebElement instance or list of x- and y-coordinates
:param params: Dictionary containing dictionary of params
:return: None
""" |
if not isinstance(source_element, WebElement):
source_element = self.get_visible_element(source_element, params['source'] if params else None)
if not isinstance(target_element, WebElement) and not isinstance(target_element, list):
source_element = self.get_visible_element(target_element, params['target'] if params else None)
action = ActionChains(self.driver)
if isinstance(target_element, WebElement):
action.drag_and_drop(source_element, target_element)
else:
action.click_and_hold(source_element).move_by_offset(*target_element).release()
action.perform() |
<SYSTEM_TASK:>
Get element present in the DOM.
<END_TASK>
<USER_TASK:>
Description:
def get_present_element(self, locator, params=None, timeout=None, visible=False, parent=None):
"""
Get element present in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param locator: element identifier
:param params: (optional) locator parameters
:param timeout: (optional) time to wait for element (default: self._explicit_wait)
:param visible: (optional) if the element should also be visible (default: False)
:param parent: internal (see #get_present_child)
:return: WebElement instance
""" |
error_msg = "Child was never present" if parent else "Element was never present!"
expected_condition = ec.visibility_of_element_located if visible else ec.presence_of_element_located
return self._get(locator, expected_condition, params, timeout, error_msg, parent) |
<SYSTEM_TASK:>
Get element both present AND visible in the DOM.
<END_TASK>
<USER_TASK:>
Description:
def get_visible_element(self, locator, params=None, timeout=None):
"""
Get element both present AND visible in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param locator: locator tuple
:param params: (optional) locator params
:param timeout: (optional) time to wait for element (default: self._explicit_wait)
:return: WebElement instance
""" |
return self.get_present_element(locator, params, timeout, True) |
<SYSTEM_TASK:>
Get elements present in the DOM.
<END_TASK>
<USER_TASK:>
Description:
def get_present_elements(self, locator, params=None, timeout=None, visible=False, parent=None):
"""
Get elements present in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param locator: element identifier
:param params: (optional) locator parameters
:param timeout: (optional) time to wait for element (default: self._explicit_wait)
:param visible: (optional) if the element should also be visible (default: False)
:param parent: internal (see #get_present_children)
:return: WebElement instance
""" |
error_msg = "Children were never present" if parent else "Elements were never present!"
expected_condition = ec.visibility_of_all_elements_located if visible else ec.presence_of_all_elements_located
return self._get(locator, expected_condition, params, timeout, error_msg, parent) |
<SYSTEM_TASK:>
Get elements both present AND visible in the DOM.
<END_TASK>
<USER_TASK:>
Description:
def get_visible_elements(self, locator, params=None, timeout=None):
"""
Get elements both present AND visible in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param locator: locator tuple
:param params: (optional) locator params
:param timeout: (optional) time to wait for element (default: self._explicit_wait)
:return: WebElement instance
""" |
return self.get_present_elements(locator, params, timeout, True) |
<SYSTEM_TASK:>
Get child-element present in the DOM.
<END_TASK>
<USER_TASK:>
Description:
def get_present_child(self, parent, locator, params=None, timeout=None, visible=False):
"""
Get child-element present in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param parent: parent-element
:param locator: locator tuple
:param params: (optional) locator params
:param timeout: (optional) time to wait for element (default: self._explicit_wait)
:param visible: (optional) if the element should also be visible (default: False)
:return: WebElement instance
""" |
return self.get_present_element(locator, params, timeout, visible, parent=parent) |
<SYSTEM_TASK:>
Get child-element both present AND visible in the DOM.
<END_TASK>
<USER_TASK:>
Description:
def get_visible_child(self, parent, locator, params=None, timeout=None):
"""
Get child-element both present AND visible in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param parent: parent-element
:param locator: locator tuple
:param params: (optional) locator params
:param timeout: (optional) time to wait for element (default: self._explicit_wait)
:return: WebElement instance
""" |
return self.get_present_child(parent, locator, params, timeout, True) |
<SYSTEM_TASK:>
Get child-elements both present in the DOM.
<END_TASK>
<USER_TASK:>
Description:
def get_present_children(self, parent, locator, params=None, timeout=None, visible=False):
"""
Get child-elements both present in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param parent: parent-element
:param locator: locator tuple
:param params: (optional) locator params
:param timeout: (optional) time to wait for element (default: self._explicit_wait)
:param visible: (optional) if the element should also be visible (default: False)
:return: WebElement instance
""" |
return self.get_present_elements(locator, params, timeout, visible, parent=parent) |
<SYSTEM_TASK:>
Get child-elements both present AND visible in the DOM.
<END_TASK>
<USER_TASK:>
Description:
def get_visible_children(self, parent, locator, params=None, timeout=None):
"""
Get child-elements both present AND visible in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param parent: parent-element
:param locator: locator tuple
:param params: (optional) locator params
:param timeout: (optional) time to wait for element (default: self._explicit_wait)
:return: WebElement instance
""" |
return self.get_present_children(parent, locator, params, timeout, True) |
<SYSTEM_TASK:>
Get elements based on locator with optional parameters.
<END_TASK>
<USER_TASK:>
Description:
def _get(self, locator, expected_condition, params=None, timeout=None, error_msg="", driver=None, **kwargs):
"""
Get elements based on locator with optional parameters.
Uses selenium.webdriver.support.expected_conditions to determine the state of the element(s).
:param locator: element identifier
:param expected_condition: expected condition of element (ie. visible, clickable, etc)
:param params: (optional) locator parameters
:param timeout: (optional) time to wait for element (default: self._explicit_wait)
:param error_msg: (optional) customized error message
:param driver: (optional) alternate Webdriver instance (example: parent-element)
:param kwargs: optional arguments to expected conditions
:return: WebElement instance, list of WebElements, or None
""" |
from selenium.webdriver.support.ui import WebDriverWait
if not isinstance(locator, WebElement):
error_msg += "\nLocator of type <{}> with selector <{}> with params <{params}>".format(
*locator, params=params)
locator = self.__class__.get_compliant_locator(*locator, params=params)
_driver = driver or self.driver
exp_cond = expected_condition(locator, **kwargs)
if timeout == 0:
try:
return exp_cond(_driver)
except NoSuchElementException:
return None
if timeout is None:
timeout = self._explicit_wait
error_msg += "\nExpected condition: {}" \
"\nTimeout: {}".format(expected_condition, timeout)
return WebDriverWait(_driver, timeout).until(exp_cond, error_msg) |
<SYSTEM_TASK:>
Scrolls an element into view.
<END_TASK>
<USER_TASK:>
Description:
def scroll_element_into_view(self, selector):
"""
Scrolls an element into view.
:param selector: selector of element or WebElement to scroll into view
:return: None
""" |
element = selector
if isinstance(element, WebElement):
self.execute_script("arguments[0].scrollIntoView( true );", element)
else:
self.execute_script("$('{}')[0].scrollIntoView( true );".format(selector[1])) |
<SYSTEM_TASK:>
Open a hover or popover.
<END_TASK>
<USER_TASK:>
Description:
def open_hover(self, locator, params=None, use_js=False):
"""
Open a hover or popover.
:param locator: locator tuple or WebElement instance
:param params: (optional) locator parameters
:param use_js: use javascript to open hover
:return: element hovered
""" |
element = locator
if not isinstance(element, WebElement):
element = self.get_visible_element(locator, params)
if use_js:
self._js_hover('mouseover', element)
return element
actions = ActionChains(self.driver)
actions.move_to_element(element).perform()
actions.reset_actions()
return element |
<SYSTEM_TASK:>
Close hover by moving to a set offset "away" from the element being hovered.
<END_TASK>
<USER_TASK:>
Description:
def close_hover(self, element, use_js=False):
"""
Close hover by moving to a set offset "away" from the element being hovered.
:param element: element that triggered the hover to open
:param use_js: use javascript to close hover
:return: None
""" |
try:
if use_js:
self._js_hover('mouseout', element)
else:
actions = ActionChains(self.driver)
actions.move_to_element_with_offset(element, -100, -100)
actions.reset_actions()
except (StaleElementReferenceException, MoveTargetOutOfBoundsException):
return True |
<SYSTEM_TASK:>
Hovers an element and performs whatever action is specified in the supplied function.
<END_TASK>
<USER_TASK:>
Description:
def perform_hover_action(self, locator, func, error_msg='', exceptions=None, params=None,
alt_loc=None, alt_params=None, **kwargs):
"""
Hovers an element and performs whatever action is specified in the supplied function.
NOTE: Specified function MUST return a non-false value upon success!
:param locator: locator tuple or WebElement instance
:param func: action to perform while hovering
:param error_msg: error message to display if hovering failed
:param exceptions: list of exceptions (default: StaleElementReferenceException)
:param params: (optional) locator parameters
:param alt_loc: alternate locator tuple or WebElement instance to move to with offset
:param alt_params: (optional) alternate locator parameters
:param kwargs: keyword arguments to the function func
:return: result of performed action
""" |
def _do_hover():
try:
with self.hover(locator, params, alt_loc, alt_params):
return func(**kwargs)
except exc:
return False
exc = [StaleElementReferenceException]
if exceptions is not None:
try:
exc.extend(iter(exceptions))
except TypeError: # exceptions is not iterable
exc.append(exceptions)
exc = tuple(exc)
msg = error_msg or "Performing hover actions failed!"
return ActionWait().until(_do_hover, msg) |
<SYSTEM_TASK:>
Context manager for hovering.
<END_TASK>
<USER_TASK:>
Description:
def hover(self, locator, params=None, use_js=False, alt_loc=None, alt_params=None):
"""
Context manager for hovering.
Opens and closes the hover.
Usage:
with self.hover(locator, params):
// do something with the hover
:param locator: locator tuple or WebElement instance
:param params: (optional) locator params
:param use_js: use javascript to hover
:param alt_loc: alternate locator tuple or WebElement instance for close hover
:param alt_params: (optional) alternate locator params
:return: None
""" |
# Open hover
element = self.open_hover(locator, params, use_js)
try:
yield
finally:
# Close hover
if alt_loc:
element = alt_loc
if not isinstance(element, WebElement):
element = self.get_visible_element(alt_loc, alt_params)
self.close_hover(element, use_js) |
<SYSTEM_TASK:>
Wait and get elements when they're populated with any text.
<END_TASK>
<USER_TASK:>
Description:
def wait_for_non_empty_text(self, locator, params=None, timeout=5):
"""
Wait and get elements when they're populated with any text.
:param locator: locator tuple
:param params: (optional) locator params
:param timeout: (optional) maximum waiting time (in seconds) (default: 5)
:return: list of WebElements
""" |
def _do_wait():
elements = self.get_present_elements(locator, params, timeout=0)
for element in elements:
if not self.get_text(element):
return False
return elements
return ActionWait(timeout).until(_do_wait, "Element text was never populated!") |
<SYSTEM_TASK:>
Waits for an element attribute to get a certain value.
<END_TASK>
<USER_TASK:>
Description:
def wait_for_attribute(self, locator, attribute, value, params=None, timeout=5):
"""
Waits for an element attribute to get a certain value.
Note: This function re-get's the element in a loop to avoid caching or stale element issues.
:Example:
Wait for the class attribute to get 'board-hidden' value
:param locator: locator tuple
:param attribute: element attribute
:param value: attribute value to wait for
:param params: (optional) locator params
:param timeout: (optional) maximum waiting time (in seconds) (default: 5)
:return: None
""" |
def _do_wait():
element = self.get_present_element(locator, params)
return value in self.get_attribute(element, attribute)
ActionWait(timeout).until(_do_wait, "Attribute never set!") |
<SYSTEM_TASK:>
Waits until there are no active or pending ajax requests.
<END_TASK>
<USER_TASK:>
Description:
def wait_for_ajax_calls_to_complete(self, timeout=5):
"""
Waits until there are no active or pending ajax requests.
Raises TimeoutException should silence not be had.
:param timeout: time to wait for silence (default: 5 seconds)
:return: None
""" |
from selenium.webdriver.support.ui import WebDriverWait
WebDriverWait(self.driver, timeout).until(lambda s: s.execute_script("return jQuery.active === 0")) |
<SYSTEM_TASK:>
Yield each IP4 broadcast address, and the all-broadcast
<END_TASK>
<USER_TASK:>
Description:
def _find_ip4_broadcast_addresses():
"""Yield each IP4 broadcast address, and the all-broadcast
""" |
yield "255.255.255.255"
for interface in netifaces.interfaces():
ifaddresses = netifaces.ifaddresses(interface)
for family in ifaddresses:
if family == netifaces.AF_INET:
address_info = ifaddresses[family]
for info in address_info:
if "broadcast" in info:
yield info['broadcast'] |
<SYSTEM_TASK:>
Find all the IP4 addresses currently bound to interfaces
<END_TASK>
<USER_TASK:>
Description:
def _find_ip4_addresses():
"""Find all the IP4 addresses currently bound to interfaces
""" |
global _ip4_addresses
proto = socket.AF_INET
if _ip4_addresses is None:
_ip4_addresses = []
#
# Determine the interface for the default gateway
# (if any) and, later, prioritise the INET address on
# that interface.
#
default_gateway = netifaces.gateways()['default']
if proto in default_gateway:
_, default_gateway_interface = default_gateway[proto]
else:
default_gateway_interface = None
for interface in netifaces.interfaces():
for info in netifaces.ifaddresses(interface).get(netifaces.AF_INET, []):
if info['addr']:
if interface == default_gateway_interface:
_ip4_addresses.insert(0, info['addr'])
else:
_ip4_addresses.append(info['addr'])
return _ip4_addresses |
<SYSTEM_TASK:>
Calculates the VAT rate based on a telephone number
<END_TASK>
<USER_TASK:>
Description:
def calculate_rate(phone_number, address_country_code=None, address_exception=None):
"""
Calculates the VAT rate based on a telephone number
:param phone_number:
The string phone number, in international format with leading +
:param address_country_code:
The user's country_code, as detected from billing_address or
declared_residence. This prevents an UndefinitiveError from being
raised.
:param address_exception:
The user's exception name, as detected from billing_address or
declared_residence. This prevents an UndefinitiveError from being
raised.
:raises:
ValueError - error with phone number provided
UndefinitiveError - when no address_country_code and address_exception are provided and the phone number area code matching isn't specific enough
:return:
A tuple of (Decimal percentage rate, country code, exception name [or None])
""" |
if not phone_number:
raise ValueError('No phone number provided')
if not isinstance(phone_number, str_cls):
raise ValueError('Phone number is not a string')
phone_number = phone_number.strip()
phone_number = re.sub('[^+0-9]', '', phone_number)
if not phone_number or phone_number[0] != '+':
raise ValueError('Phone number is not in international format with a leading +')
phone_number = phone_number[1:]
if not phone_number:
raise ValueError('Phone number does not appear to contain any digits')
country_code = _lookup_country_code(phone_number)
if not country_code:
raise ValueError('Phone number does not appear to be a valid international phone number')
if country_code in CALLING_CODE_EXCEPTIONS:
for info in CALLING_CODE_EXCEPTIONS[country_code]:
if not re.match(info['regex'], phone_number):
continue
mapped_country = info['country_code']
mapped_name = info['name']
if not info['definitive']:
if address_country_code is None:
raise UndefinitiveError('It is not possible to determine the users VAT rates based on the information provided')
if address_country_code != mapped_country:
continue
if address_exception != info['name']:
continue
rate = rates.BY_COUNTRY[mapped_country]['exceptions'][mapped_name]
return (rate, mapped_country, mapped_name)
if country_code not in rates.BY_COUNTRY:
return (Decimal('0.0'), country_code, None)
return (rates.BY_COUNTRY[country_code]['rate'], country_code, None) |
<SYSTEM_TASK:>
Combine the elements of a five-item iterable into a URI reference's
<END_TASK>
<USER_TASK:>
Description:
def uriunsplit(parts):
"""Combine the elements of a five-item iterable into a URI reference's
string representation.
""" |
scheme, authority, path, query, fragment = parts
if isinstance(path, bytes):
result = SplitResultBytes
else:
result = SplitResultUnicode
return result(scheme, authority, path, query, fragment).geturi() |
<SYSTEM_TASK:>
Return the re-combined version of the original URI reference as a
<END_TASK>
<USER_TASK:>
Description:
def geturi(self):
"""Return the re-combined version of the original URI reference as a
string.
""" |
scheme, authority, path, query, fragment = self
# RFC 3986 5.3. Component Recomposition
result = []
if scheme is not None:
result.extend([scheme, self.COLON])
if authority is not None:
result.extend([self.SLASH, self.SLASH, authority])
result.append(path)
if query is not None:
result.extend([self.QUEST, query])
if fragment is not None:
result.extend([self.HASH, fragment])
return self.EMPTY.join(result) |
<SYSTEM_TASK:>
Return the decoded userinfo, host and port subcomponents of the URI
<END_TASK>
<USER_TASK:>
Description:
def getauthority(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo, host and port subcomponents of the URI
authority as a three-item tuple.
""" |
# TBD: (userinfo, host, port) kwargs, default string?
if default is None:
default = (None, None, None)
elif not isinstance(default, collections.Iterable):
raise TypeError('Invalid default type')
elif len(default) != 3:
raise ValueError('Invalid default length')
# TODO: this could be much more efficient by using a dedicated regex
return (
self.getuserinfo(default[0], encoding, errors),
self.gethost(default[1], errors),
self.getport(default[2])
) |
<SYSTEM_TASK:>
Return the decoded userinfo subcomponent of the URI authority, or
<END_TASK>
<USER_TASK:>
Description:
def getuserinfo(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo subcomponent of the URI authority, or
`default` if the original URI reference did not contain a
userinfo field.
""" |
userinfo = self.userinfo
if userinfo is None:
return default
else:
return uridecode(userinfo, encoding, errors) |
<SYSTEM_TASK:>
Return the normalized decoded URI path.
<END_TASK>
<USER_TASK:>
Description:
def getpath(self, encoding='utf-8', errors='strict'):
"""Return the normalized decoded URI path.""" |
path = self.__remove_dot_segments(self.path)
return uridecode(path, encoding, errors) |
<SYSTEM_TASK:>
Return the decoded query string, or `default` if the original URI
<END_TASK>
<USER_TASK:>
Description:
def getquery(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded query string, or `default` if the original URI
reference did not contain a query component.
""" |
query = self.query
if query is None:
return default
else:
return uridecode(query, encoding, errors) |
<SYSTEM_TASK:>
Split the query component into individual `name=value` pairs
<END_TASK>
<USER_TASK:>
Description:
def getquerydict(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values for each name.
""" |
dict = collections.defaultdict(list)
for name, value in self.getquerylist(sep, encoding, errors):
dict[name].append(value)
return dict |
<SYSTEM_TASK:>
Calculates the VAT rate for a customer based on their declared country
<END_TASK>
<USER_TASK:>
Description:
def calculate_rate(country_code, exception_name):
"""
Calculates the VAT rate for a customer based on their declared country
and any declared exception information.
:param country_code:
The two-character country code where the user resides
:param exception_name:
The name of an exception for the country, as returned from
vat_moss.declared_residence.options()
:raises:
ValueError - if country_code is not two characers, or exception_name is not None or a valid exception from options()
:return:
A tuple of (Decimal VAT rate, country_code, exception name [or None])
""" |
if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2:
raise ValueError('Invalidly formatted country code')
if exception_name and not isinstance(exception_name, str_cls):
raise ValueError('Exception name is not None or a string')
country_code = country_code.upper()
if country_code not in rates.BY_COUNTRY:
return (Decimal('0.0'), country_code, None)
country_info = rates.BY_COUNTRY[country_code]
if not exception_name:
return (country_info['rate'], country_code, None)
if exception_name not in country_info['exceptions']:
raise ValueError('"%s" is not a valid exception for %s' % (exception_name, country_code))
rate_info = country_info['exceptions'][exception_name]
if isinstance(rate_info, Decimal):
rate = rate_info
else:
# This allows handling the complex case of the UK RAF bases in Cyprus
# that map to the standard country rate. The country code and exception
# name need to be changed in addition to gettting a special rate.
rate, country_code, exception_name = rate_info
return (rate, country_code, exception_name) |
<SYSTEM_TASK:>
Returns a list of exception names for the given country
<END_TASK>
<USER_TASK:>
Description:
def exceptions_by_country(country_code):
"""
Returns a list of exception names for the given country
:param country_code:
The two-character country code for the user
:raises:
ValueError - if country_code is not two characers
:return:
A list of strings that are VAT exceptions for the country specified
""" |
if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2:
raise ValueError('Invalidly formatted country code')
country_code = country_code.upper()
return EXCEPTIONS_BY_COUNTRY.get(country_code, []) |
<SYSTEM_TASK:>
Accepts a VAT ID and normaizes it, getting rid of spaces, periods, dashes
<END_TASK>
<USER_TASK:>
Description:
def normalize(vat_id):
"""
Accepts a VAT ID and normaizes it, getting rid of spaces, periods, dashes
etc and converting it to upper case.
:param vat_id:
The VAT ID to check. Allows "GR" prefix for Greece, even though it
should be "EL".
:raises:
ValueError - If the is not a string or is not in the format of two characters plus an identifier
:return:
None if the VAT ID is blank or not for an EU country or Norway
Otherwise a normalized string containing the VAT ID
""" |
if not vat_id:
return None
if not isinstance(vat_id, str_cls):
raise ValueError('VAT ID is not a string')
if len(vat_id) < 3:
raise ValueError('VAT ID must be at least three character long')
# Normalize the ID for simpler regexes
vat_id = re.sub('\\s+', '', vat_id)
vat_id = vat_id.replace('-', '')
vat_id = vat_id.replace('.', '')
vat_id = vat_id.upper()
country_prefix = vat_id[0:2]
# Fix people using GR prefix for Greece
if country_prefix == 'GR':
vat_id = 'EL' + vat_id[2:]
country_prefix = 'EL'
if country_prefix not in ID_PATTERNS:
return None
return vat_id |
<SYSTEM_TASK:>
Decorator to handle stale element reference exceptions.
<END_TASK>
<USER_TASK:>
Description:
def handle_stale(msg='', exceptions=None):
"""
Decorator to handle stale element reference exceptions.
:param msg: Error message
:param exceptions: Extra exceptions to handle
:return: the result of the decorated function
""" |
exc = [StaleElementReferenceException]
if exceptions is not None:
try:
exc.extend(iter(exceptions))
except TypeError: # exceptions is not iterable
exc.append(exceptions)
exc = tuple(exc)
if not msg:
msg = "Could not recover from Exception(s): {}".format(', '.join([e.__name__ for e in exc]))
def wrapper(func):
def exc_handler(*args, **kwargs):
import time
timeout = 10
poll_freq = 0.5
end_time = time.time() + timeout
while time.time() <= end_time:
try:
return func(*args, **kwargs)
except exc:
time.sleep(poll_freq)
poll_freq *= 1.25
continue
raise RuntimeError(msg)
return exc_handler
return wrapper |
<SYSTEM_TASK:>
Decorator to handle generic waiting situations.
<END_TASK>
<USER_TASK:>
Description:
def wait(msg='', exceptions=None, timeout=10):
"""
Decorator to handle generic waiting situations.
Will handle StaleElementReferenceErrors.
:param msg: Error message
:param exceptions: Extra exceptions to handle
:param timeout: time to keep trying (default: 10 seconds)
:return: the result of the decorated function
""" |
exc = [StaleElementReferenceException]
if exceptions is not None:
try:
exc.extend(iter(exceptions))
except TypeError: # exceptions is not iterable
exc.append(exceptions)
exc = tuple(exc)
if not msg:
msg = "Could not recover from Exception(s): {}".format(', '.join([e.__name__ for e in exc]))
def wrapper(func):
def wait_handler(*args, **kwargs):
import time
poll_freq = 0.5
end_time = time.time() + timeout
while time.time() <= end_time:
try:
value = func(*args, **kwargs)
if value:
return value
except exc as e:
LOGGER.debug(e)
pass # continue
time.sleep(poll_freq)
poll_freq *= 1.25
raise RuntimeError(msg)
return wait_handler
return wrapper |
<SYSTEM_TASK:>
Calculates the VAT rate that should be collected based on address
<END_TASK>
<USER_TASK:>
Description:
def calculate_rate(country_code, postal_code, city):
"""
Calculates the VAT rate that should be collected based on address
information provided
:param country_code:
The two-character country code
:param postal_code:
The postal code for the user
:param city:
The city name for the user
:raises:
ValueError - If country code is not two characers, or postal_code or city are not strings. postal_code may be None or blank string for countries without postal codes.
:return:
A tuple of (Decimal percentage rate, country code, exception name [or None])
""" |
if not country_code or not isinstance(country_code, str_cls):
raise ValueError('Invalidly formatted country code')
country_code = country_code.strip()
if len(country_code) != 2:
raise ValueError('Invalidly formatted country code')
country_code = country_code.upper()
if country_code not in COUNTRIES_WITHOUT_POSTAL_CODES:
if not postal_code or not isinstance(postal_code, str_cls):
raise ValueError('Postal code is not a string')
if not city or not isinstance(city, str_cls):
raise ValueError('City is not a string')
if isinstance(postal_code, str_cls):
postal_code = re.sub('\\s+', '', postal_code)
postal_code = postal_code.upper()
# Remove the common european practice of adding the country code
# to the beginning of a postal code, followed by a dash
if len(postal_code) > 3 and postal_code[0:3] == country_code + '-':
postal_code = postal_code[3:]
postal_code = postal_code.replace('-', '')
city = city.lower().strip()
if country_code not in rates.BY_COUNTRY and country_code not in POSTAL_CODE_EXCEPTIONS:
return (Decimal('0.0'), country_code, None)
country_default = rates.BY_COUNTRY.get(country_code, {'rate': Decimal('0.0')})['rate']
if country_code not in POSTAL_CODE_EXCEPTIONS:
return (country_default, country_code, None)
exceptions = POSTAL_CODE_EXCEPTIONS[country_code]
for matcher in exceptions:
# Postal code-only match
if isinstance(matcher, str_cls):
postal_regex = matcher
city_regex = None
else:
postal_regex, city_regex = matcher
if not re.match(postal_regex, postal_code):
continue
if city_regex and not re.search(city_regex, city):
continue
mapped_country = exceptions[matcher]['country_code']
# There is at least one entry where we map to a different country,
# but are not mapping to an exception
if 'name' not in exceptions[matcher]:
country_code = mapped_country
country_default = rates.BY_COUNTRY[country_code]['rate']
break
mapped_name = exceptions[matcher]['name']
rate = rates.BY_COUNTRY[mapped_country]['exceptions'][mapped_name]
return (rate, mapped_country, mapped_name)
return (country_default, country_code, None) |
<SYSTEM_TASK:>
Get measurements of a device.
<END_TASK>
<USER_TASK:>
Description:
def async_get_measurements(self, uid, fields='*'):
"""Get measurements of a device.""" |
return (yield from self._get('/pods/{}/measurements'.format(uid),
fields=fields))[0] |
<SYSTEM_TASK:>
Get log entries of a device.
<END_TASK>
<USER_TASK:>
Description:
def async_get_ac_states(self, uid, limit=1, offset=0, fields='*'):
"""Get log entries of a device.""" |
return (yield from self._get('/pods/{}/acStates'.format(uid),
limit=limit,
fields=fields,
offset=offset)) |
<SYSTEM_TASK:>
Set a specific device property.
<END_TASK>
<USER_TASK:>
Description:
def async_set_ac_state_property(
self, uid, name, value, ac_state=None, assumed_state=False):
"""Set a specific device property.""" |
if ac_state is None:
ac_state = yield from self.async_get_ac_states(uid)
ac_state = ac_state[0]['acState']
data = {
'currentAcState': ac_state,
'newValue': value
}
if assumed_state:
data['reason'] = "StateCorrectionByUser"
resp = yield from self._session.patch(
_SERVER + '/pods/{}/acStates/{}'.format(uid, name),
data=json.dumps(data),
params=self._params,
timeout=self._timeout)
try:
return (yield from resp.json())['result']
except aiohttp.client_exceptions.ContentTypeError:
pass
raise SensiboError((yield from resp.text())) |
<SYSTEM_TASK:>
Attempt to bind a socket a number of times with a short interval in between
<END_TASK>
<USER_TASK:>
Description:
def _bind_with_timeout(bind_function, args, n_tries=3, retry_interval_s=0.5):
"""Attempt to bind a socket a number of times with a short interval in between
Especially on Linux, crashing out of a networkzero process can leave the sockets
lingering and unable to re-bind on startup. We give it a few goes here to see if
we can bind within a couple of seconds.
""" |
n_tries_left = n_tries
while n_tries_left > 0:
try:
return bind_function(*args)
except zmq.error.ZMQError as exc:
_logger.warn("%s; %d tries remaining", exc, n_tries_left)
n_tries_left -= 1
except OSError as exc:
if exc.errno == errno.EADDRINUSE:
_logger.warn("%s; %d tries remaining", exc, n_tries_left)
n_tries_left -= 1
else:
raise
else:
raise core.SocketAlreadyExistsError("Failed to bind after %s tries" % n_tries) |
<SYSTEM_TASK:>
Start a beacon thread within this process if no beacon is currently
<END_TASK>
<USER_TASK:>
Description:
def _start_beacon(port=None):
"""Start a beacon thread within this process if no beacon is currently
running on this machine.
In general this is called automatically when an attempt is made to
advertise or discover. It might be convenient, though, to call this
function directly if you want to have a process whose only job is
to host this beacon so that it doesn't shut down when other processes
shut down.
""" |
global _beacon
if _beacon is None:
_logger.debug("About to start beacon with port %s", port)
try:
_beacon = _Beacon(port)
except (OSError, socket.error) as exc:
if exc.errno == errno.EADDRINUSE:
_logger.warn("Beacon already active on this machine")
#
# _remote_beacon is simply a not-None sentinel value
# to distinguish between the case where we have not
# yet started a beacon and where we have found one
# in another process.
#
_beacon = _remote_beacon
else:
raise
else:
_beacon.start() |
<SYSTEM_TASK:>
If the command RPC socket has an incoming request,
<END_TASK>
<USER_TASK:>
Description:
def poll_command_request(self):
"""If the command RPC socket has an incoming request,
separate it into its action and its params and put it
on the command request queue.
""" |
try:
message = self.rpc.recv(zmq.NOBLOCK)
except zmq.ZMQError as exc:
if exc.errno == zmq.EAGAIN:
return
else:
raise
_logger.debug("Received command %s", message)
segments = _unpack(message)
action, params = segments[0], segments[1:]
_logger.debug("Adding %s, %s to the request queue", action, params)
self._command = _Command(action, params) |
<SYSTEM_TASK:>
If the latest request has a response, issue it as a
<END_TASK>
<USER_TASK:>
Description:
def poll_command_reponse(self):
"""If the latest request has a response, issue it as a
reply to the RPC socket.
""" |
if self._command.response is not Empty:
_logger.debug("Sending response %s", self._command.response)
self.rpc.send(_pack(self._command.response))
self._command = None |
<SYSTEM_TASK:>
Calculates the VAT rate from the data returned by a GeoLite2 database
<END_TASK>
<USER_TASK:>
Description:
def calculate_rate(country_code, subdivision, city, address_country_code=None, address_exception=None):
"""
Calculates the VAT rate from the data returned by a GeoLite2 database
:param country_code:
Two-character country code
:param subdivision:
The first subdivision name
:param city:
The city name
:param address_country_code:
The user's country_code, as detected from billing_address or
declared_residence. This prevents an UndefinitiveError from being
raised.
:param address_exception:
The user's exception name, as detected from billing_address or
declared_residence. This prevents an UndefinitiveError from being
raised.
:raises:
ValueError - if country code is not two characers, or subdivision or city are not strings
UndefinitiveError - when no address_country_code and address_exception are provided and the geoip2 information is not specific enough
:return:
A tuple of (Decimal percentage rate, country code, exception name [or None])
""" |
if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2:
raise ValueError('Invalidly formatted country code')
if not isinstance(subdivision, str_cls):
raise ValueError('Subdivision is not a string')
if not isinstance(city, str_cls):
raise ValueError('City is not a string')
country_code = country_code.upper()
subdivision = subdivision.lower()
city = city.lower()
if country_code not in rates.BY_COUNTRY:
return (Decimal('0.0'), country_code, None)
country_default = rates.BY_COUNTRY[country_code]['rate']
if country_code not in GEOIP2_EXCEPTIONS:
return (country_default, country_code, None)
exceptions = GEOIP2_EXCEPTIONS[country_code]
for matcher in exceptions:
# Subdivision-only match
if isinstance(matcher, str_cls):
sub_match = matcher
city_match = None
else:
sub_match, city_match = matcher
if sub_match != subdivision:
continue
if city_match and city_match != city:
continue
info = exceptions[matcher]
exception_name = info['name']
if not info['definitive']:
if address_country_code is None:
raise UndefinitiveError('It is not possible to determine the users VAT rates based on the information provided')
if address_country_code != country_code:
continue
if address_exception != exception_name:
continue
rate = rates.BY_COUNTRY[country_code]['exceptions'][exception_name]
return (rate, country_code, exception_name)
return (country_default, country_code, None) |
<SYSTEM_TASK:>
If using the Python money package, this will set up the xrates exchange
<END_TASK>
<USER_TASK:>
Description:
def setup_xrates(base, rates):
"""
If using the Python money package, this will set up the xrates exchange
rate data.
:param base:
The string currency code to use as the base
:param rates:
A dict with keys that are string currency codes and values that are
a Decimal of the exchange rate for that currency.
""" |
xrates.install('money.exchange.SimpleBackend')
xrates.base = base
for code, value in rates.items():
xrates.setrate(code, value) |
<SYSTEM_TASK:>
Formats a decimal or Money object into an unambiguous string representation
<END_TASK>
<USER_TASK:>
Description:
def format(amount, currency=None):
"""
Formats a decimal or Money object into an unambiguous string representation
for the purpose of invoices in English.
:param amount:
A Decimal or Money object
:param currency:
If the amount is a Decimal, the currency of the amount
:return:
A string representation of the amount in the currency
""" |
if currency is None and hasattr(amount, 'currency'):
currency = amount.currency
# Allow Money objects
if not isinstance(amount, Decimal) and hasattr(amount, 'amount'):
amount = amount.amount
if not isinstance(currency, str_cls):
raise ValueError('The currency specified is not a string')
if currency not in FORMATTING_RULES:
valid_currencies = sorted(FORMATTING_RULES.keys())
formatted_currencies = ', '.join(valid_currencies)
raise ValueError('The currency specified, "%s", is not a supported currency: %s' % (currency, formatted_currencies))
if not isinstance(amount, Decimal):
raise ValueError('The amount specified is not a Decimal')
rules = FORMATTING_RULES[currency]
format_string = ',.%sf' % rules['decimal_places']
result = builtin_format(amount, format_string)
result = result.replace(',', '_')
result = result.replace('.', '|')
result = result.replace('_', rules['thousands_separator'])
result = result.replace('|', rules['decimal_mark'])
if rules['symbol_first']:
result = rules['symbol'] + result
else:
result = result + rules['symbol']
return result |
<SYSTEM_TASK:>
Gets a momentum by the given name.
<END_TASK>
<USER_TASK:>
Description:
def get_momentum_by_name(self, name):
"""Gets a momentum by the given name.
:param name: the momentum name.
:returns: a momentum found.
:raises TypeError: `name` is ``None``.
:raises KeyError: failed to find a momentum named `name`.
""" |
if name is None:
raise TypeError('\'name\' should not be None')
for momentum in self.momenta:
if momentum.name == name:
return momentum
raise KeyError('No such momentum named {0}'.format(name)) |
<SYSTEM_TASK:>
Removes and returns a momentum by the given name.
<END_TASK>
<USER_TASK:>
Description:
def pop_momentum_by_name(self, name):
"""Removes and returns a momentum by the given name.
:param name: the momentum name.
:returns: a momentum removed.
:raises TypeError: `name` is ``None``.
:raises KeyError: failed to find a momentum named `name`.
""" |
momentum = self.get_momentum_by_name(name)
self.remove_momentum(momentum)
return momentum |
<SYSTEM_TASK:>
Updates a momentum by the given name.
<END_TASK>
<USER_TASK:>
Description:
def update_momentum_by_name(self, name, **kwargs):
"""Updates a momentum by the given name.
:param name: the momentum name.
:param velocity: (keyword-only) a new value for `velocity`.
:param since: (keyword-only) a new value for `since`.
:param until: (keyword-only) a new value for `until`.
:returns: a momentum updated.
:raises TypeError: `name` is ``None``.
:raises KeyError: failed to find a momentum named `name`.
""" |
momentum = self.pop_momentum_by_name(name)
velocity, since, until = momentum[:3]
velocity = kwargs.get('velocity', velocity)
since = kwargs.get('since', since)
until = kwargs.get('until', until)
return self.add_momentum(velocity, since, until, name) |
<SYSTEM_TASK:>
Changes the velocity of a momentum named `name`.
<END_TASK>
<USER_TASK:>
Description:
def snap_momentum_by_name(self, name, velocity, at=None):
"""Changes the velocity of a momentum named `name`.
:param name: the momentum name.
:param velocity: a new velocity.
:param at: the time to snap. (default: now)
:returns: a momentum updated.
:raises TypeError: `name` is ``None``.
:raises KeyError: failed to find a momentum named `name`.
""" |
at = now_or(at)
self.forget_past(at=at)
return self.update_momentum_by_name(name, velocity=velocity, since=at) |
<SYSTEM_TASK:>
Compose a URI reference string from its individual components.
<END_TASK>
<USER_TASK:>
Description:
def uricompose(scheme=None, authority=None, path='', query=None,
fragment=None, userinfo=None, host=None, port=None,
querysep='&', encoding='utf-8'):
"""Compose a URI reference string from its individual components.""" |
# RFC 3986 3.1: Scheme names consist of a sequence of characters
# beginning with a letter and followed by any combination of
# letters, digits, plus ("+"), period ("."), or hyphen ("-").
# Although schemes are case-insensitive, the canonical form is
# lowercase and documents that specify schemes must do so with
# lowercase letters. An implementation should accept uppercase
# letters as equivalent to lowercase in scheme names (e.g., allow
# "HTTP" as well as "http") for the sake of robustness but should
# only produce lowercase scheme names for consistency.
if isinstance(scheme, bytes):
scheme = _scheme(scheme)
elif scheme is not None:
scheme = _scheme(scheme.encode())
# authority must be string type or three-item iterable
if authority is None:
authority = (None, None, None)
elif isinstance(authority, bytes):
authority = _AUTHORITY_RE_BYTES.match(authority).groups()
elif isinstance(authority, _unicode):
authority = _AUTHORITY_RE_UNICODE.match(authority).groups()
elif not isinstance(authority, collections.Iterable):
raise TypeError('Invalid authority type')
elif len(authority) != 3:
raise ValueError('Invalid authority length')
authority = _authority(
userinfo if userinfo is not None else authority[0],
host if host is not None else authority[1],
port if port is not None else authority[2],
encoding
)
# RFC 3986 3.3: If a URI contains an authority component, then the
# path component must either be empty or begin with a slash ("/")
# character. If a URI does not contain an authority component,
# then the path cannot begin with two slash characters ("//").
path = uriencode(path, _SAFE_PATH, encoding)
if authority is not None and path and not path.startswith(b'/'):
raise ValueError('Invalid path with authority component')
if authority is None and path.startswith(b'//'):
raise ValueError('Invalid path without authority component')
# RFC 3986 4.2: A path segment that contains a colon character
# (e.g., "this:that") cannot be used as the first segment of a
# relative-path reference, as it would be mistaken for a scheme
# name. Such a segment must be preceded by a dot-segment (e.g.,
# "./this:that") to make a relative-path reference.
if scheme is None and authority is None and not path.startswith(b'/'):
if b':' in path.partition(b'/')[0]:
path = b'./' + path
# RFC 3986 3.4: The characters slash ("/") and question mark ("?")
# may represent data within the query component. Beware that some
# older, erroneous implementations may not handle such data
# correctly when it is used as the base URI for relative
# references (Section 5.1), apparently because they fail to
# distinguish query data from path data when looking for
# hierarchical separators. However, as query components are often
# used to carry identifying information in the form of "key=value"
# pairs and one frequently used value is a reference to another
# URI, it is sometimes better for usability to avoid percent-
# encoding those characters.
if isinstance(query, _strtypes):
query = uriencode(query, _SAFE_QUERY, encoding)
elif isinstance(query, collections.Mapping):
query = _querydict(query, querysep, encoding)
elif isinstance(query, collections.Iterable):
query = _querylist(query, querysep, encoding)
elif query is not None:
raise TypeError('Invalid query type')
# RFC 3986 3.5: The characters slash ("/") and question mark ("?")
# are allowed to represent data within the fragment identifier.
# Beware that some older, erroneous implementations may not handle
# this data correctly when it is used as the base URI for relative
# references.
if fragment is not None:
fragment = uriencode(fragment, _SAFE_FRAGMENT, encoding)
result = uriunsplit((scheme, authority, path, query, fragment))
# always return platform `str` type
return result if isinstance(result, str) else result.decode() |
<SYSTEM_TASK:>
Continues to execute the function until successful or time runs out.
<END_TASK>
<USER_TASK:>
Description:
def until(self, func, message='', *args, **kwargs):
"""
Continues to execute the function until successful or time runs out.
:param func: function to execute
:param message: message to print if time ran out
:param args: arguments
:param kwargs: key word arguments
:return: result of function or None
""" |
value = None
end_time = time.time() + self._timeout
while True:
value = func(*args, **kwargs)
if self._debug:
print("Value from func within ActionWait: {}".format(value))
if value:
break
time.sleep(self._poll)
self._poll *= 1.25
if time.time() > end_time:
raise RuntimeError(message)
return value |
<SYSTEM_TASK:>
Return string representation of the device, including
<END_TASK>
<USER_TASK:>
Description:
def describe_connection(self):
"""Return string representation of the device, including
the connection state""" |
if self.device==None:
return "%s [disconnected]" % (self.name)
else:
return "%s connected to %s %s version: %s [serial: %s]" % (self.name,
self.vendor_name, self.product_name,
self.version_number, self.serial_number) |
<SYSTEM_TASK:>
Send a new event with the given information. Requires a name, runbook,
<END_TASK>
<USER_TASK:>
Description:
def send_event(
name,
runbook,
status,
output,
team,
page=False,
tip=None,
notification_email=None,
check_every='30s',
realert_every=-1,
alert_after='0s',
dependencies=[],
irc_channels=None,
slack_channels=None,
ticket=False,
project=None,
priority=None,
source=None,
tags=[],
ttl=None,
sensu_host='169.254.255.254',
sensu_port=3030,
component=None,
description=None,
):
"""Send a new event with the given information. Requires a name, runbook,
status code, event output, and team but the other keys are kwargs and have
defaults.
:type name: str
:param name: Name of the check
:type runbook: str
:param runbook: The runbook associated with the check
:type status: int
:param status: Exit status code, 0,1,2,3. Must comply with the Nagios
conventions. See `the Sensu docs <https://sensuapp.org/docs/latest/checks#sensu-check-specification>`_
for the exact specification.
:type output: str
:param output: The output of the check itself. May include CRIT/WARN/OK to make
it easy to evaluate how things went. Should be newline separated,
but try to put the most relevant data in the first line.
Example:
OK: Everything is fine
or
CRIT: Accounts are locked. Users can't buy widgets.
:type team: str
:param team: Team responsible for this check. This team must already be defined
server-side in the Sensu handler configuration.
:type page: bool
:param page: Boolean on whether this alert is page-worthy. Activates
handlers that send pages.
:type tip: str
:param tip: A short 1-line version of the runbook. Example:
"Set clip-jawed monodish to 6"
:type notification_email: str
:param notification_email: A comma-separated string of email destinations. Unset will
default to the "team" default.
:type check_every: str
:param check_every: Human readable time unit to let Sensu know how of then
this event is fired. Defaults to "30s". If this parameter
is not set correctly, the math for `alert_after` will be
incorrect.
:type realert_every: int
:param realert_every: Integer value for filtering repeat occurrences. A
value of 2 would send every other alert. Defaults to -1,
which is a special value representing exponential backoff.
(alerts on event number 1,2,4,8, etc)
:type alert_after: str
:param alert_after: A human readable time unit to suspend handler action until
enough occurrences have taken place. Only valid when
check_every is accurate.
:type dependencies: list
:param dependencies: An list of strings representing checks that *this*
check is dependent on.
:type irc_channels: list
:param irc_channels: An list of IRC channels to send the event
notification to. Defaults to the team setting. Set an empty
list to specify no IRC notifications.
:type slack_channels: list
:param slack_channels: An list of Slack channels to send the event
notification to. Defaults to the team setting. Set an empty
list to specify no Slack notifications.
:type ticket: bool
:param ticket: A Boolean value to enable ticket creation. Defaults to false.
:type project: str
:param project: A string representing the JIRA project that the ticket
should go under. Defaults to the team value.
:type priority: str
:param priority: A JIRA priority to use when creating a ticket. This only
makes sense to use when in combination with the ticket
parameter set to true.
:type source: str
:param source: Allows "masquerading" the source value of the event,
otherwise comes from the fqdn of the host it runs on.
This is especially important to set on events that could
potentially be created from multiple hosts. For example if
``send_event`` is called from three different hosts in a cluster,
you wouldn't want three different events, you would only want
one event that looked like it came from ``the_cluster``, so
you would set ``source='the_cluster'``.
:type tags: list
:param tags: An list of arbitrary tags that can be used in handlers for
different metadata needs such as labels in JIRA handlers.
:type ttl: str
:param ttl: A human readable time unit to set the check TTL. If Sensu does
not hear from the check after this time unit, Sensu will spawn a
new failing event! (aka check staleness) Defaults to None,
meaning Sensu will only spawn events when send_event is called.
:type sensu_host: str
:param sensu_host: The IP or Name to connect to for sending the event.
Defaults to the yocalhost IP.
:type component: list
:param component: Component(s) affected by the event. Good example here would
would be to include the service that is being affected or a
module of that service such as healthcheck.
:type description: str
:param description: Human readable text giving more context on the event. This could
include information on what the check means or why was it
created.
Note on TTL events and alert_after:
``alert_after`` and ``check_every`` only really make sense on events that are created
periodically. Setting ``alert_after`` on checks that are not periodic is not advised
because the math will be incorrect. For example, if check was written that called
``send_event`` on minute values that were prime, what should the ``check_every`` setting
be? No matter what it was, it would be wrong, and therefore ``alert_after`` would be incorrectly
calculated (as it is a function of the number of failing events seen multiplied by the ``check_every``
setting). If in doubt, set ``alert_after`` to ``0`` to ensure you never miss an alert
due to incorrect ``alert_after`` math on non-periodic events. (See also this
`Pull request <https://github.com/sensu/sensu/pull/1200>`_)
""" |
if not (name and team):
raise ValueError("Name and team must be present")
if not re.match(r'^[\w\.-]+$', name):
raise ValueError("Name cannot contain special characters")
if not runbook:
runbook = 'Please set a runbook!'
result_dict = {
'name': name,
'status': status,
'output': output,
'handler': 'default',
'team': team,
'runbook': runbook,
'tip': tip,
'notification_email': notification_email,
'interval': human_to_seconds(check_every),
'page': page,
'realert_every': int(realert_every),
'dependencies': dependencies,
'alert_after': human_to_seconds(alert_after),
'ticket': ticket,
'project': project,
'priority': priority,
'source': source,
'tags': tags,
'ttl': human_to_seconds(ttl),
}
if irc_channels is not None:
result_dict['irc_channels'] = irc_channels
if slack_channels is not None:
result_dict['slack_channels'] = slack_channels
if component is not None:
result_dict['component'] = component
if description is not None:
result_dict['description'] = description
json_hash = json.dumps(result_dict)
sock = socket.socket()
try:
sock.connect((sensu_host, sensu_port))
sock.sendall(six.b(json_hash) + b'\n')
finally:
sock.close() |
<SYSTEM_TASK:>
Encode a URI string or string component.
<END_TASK>
<USER_TASK:>
Description:
def uriencode(uristring, safe='', encoding='utf-8', errors='strict'):
"""Encode a URI string or string component.""" |
if not isinstance(uristring, bytes):
uristring = uristring.encode(encoding, errors)
if not isinstance(safe, bytes):
safe = safe.encode('ascii')
try:
encoded = _encoded[safe]
except KeyError:
encoded = _encoded[b''][:]
for i in _tointseq(safe):
encoded[i] = _fromint(i)
_encoded[safe] = encoded
return b''.join(map(encoded.__getitem__, _tointseq(uristring))) |
<SYSTEM_TASK:>
Decode a URI string or string component.
<END_TASK>
<USER_TASK:>
Description:
def uridecode(uristring, encoding='utf-8', errors='strict'):
"""Decode a URI string or string component.""" |
if not isinstance(uristring, bytes):
uristring = uristring.encode(encoding or 'ascii', errors)
parts = uristring.split(b'%')
result = [parts[0]]
append = result.append
decode = _decoded.get
for s in parts[1:]:
append(decode(s[:2], b'%' + s[:2]))
append(s[2:])
if encoding is not None:
return b''.join(result).decode(encoding, errors)
else:
return b''.join(result) |
<SYSTEM_TASK:>
Check length of array or convert scalar to array.
<END_TASK>
<USER_TASK:>
Description:
def _convert_to_array(x, size, name):
"""Check length of array or convert scalar to array.
Check to see is `x` has the given length `size`. If this is true
then return Numpy array equivalent of `x`. If not then raise
ValueError, using `name` as an idnetification. If len(x) returns
TypeError, then assume it is a scalar and create a Numpy array of
length `size`. Each item of this array will have the value as `x`.
""" |
try:
l = len(x)
if l != size:
raise ValueError(
"{0} must be scalar or of length {1}".format(
name, size))
except TypeError:
# Only one item
xa = np.array([x] * size) # Each item is a diff. object.
else:
xa = np.array(x)
return xa |
<SYSTEM_TASK:>
If a label occurs more than once, add num. as suffix.
<END_TASK>
<USER_TASK:>
Description:
def unique_labels(line_labels):
"""If a label occurs more than once, add num. as suffix.""" |
from collections import defaultdict
d = defaultdict(int)
for i in line_labels:
d[i] += 1
d = dict((i, k) for i, k in d.items() if k != 1)
line_labels_u = []
for lab in reversed(line_labels):
c = d.get(lab, 0)
if c >= 1:
v = lab + "_num_" + str(c)
d[lab] -= 1
else:
v = lab
line_labels_u.insert(0, v)
return line_labels_u |
<SYSTEM_TASK:>
Box loc in data coords, given Fig. coords offset from arrow_tip.
<END_TASK>
<USER_TASK:>
Description:
def get_box_loc(fig, ax, line_wave, arrow_tip, box_axes_space=0.06):
"""Box loc in data coords, given Fig. coords offset from arrow_tip.
Parameters
----------
fig: matplotlib Figure artist
Figure on which the boxes will be placed.
ax: matplotlib Axes artist
Axes on which the boxes will be placed.
arrow_tip: list or array of floats
Location of tip of arrow, in data coordinates.
box_axes_space: float
Vertical space between arrow tip and text box in figure
coordinates. Default is 0.06.
Returns
-------
box_loc: list of floats
Box locations in data coordinates.
Notes
-----
Note that this function is not needed if user provides both arrow
tip positions and box locations. The use case is when the program
has to automatically find positions of boxes. In the automated
plotting case, the arrow tip is set to be the top of the Axes
(outside this function) and the box locations are determined by
`box_axes_space`.
In Matplotlib annotate function, both the arrow tip and the box
location can be specified. While calculating automatic box
locations, it is not ideal to use data coordinates to calculate
box location, since plots will not have a uniform appearance. Given
locations of arrow tips, and a spacing in figure fraction, this
function will calculate the box locations in data
coordinates. Using this boxes can be placed in a uniform manner.
""" |
# Plot boxes in their original x position, at a height given by the
# key word box_axes_spacing above the arrow tip. The default
# is set to 0.06. This is in figure fraction so that the spacing
# doesn't depend on the data y range.
box_loc = []
fig_inv_trans = fig.transFigure.inverted()
for w, a in zip(line_wave, arrow_tip):
# Convert position of tip of arrow to figure coordinates, add
# the vertical space between top edge and text box in figure
# fraction. Convert this text box position back to data
# coordinates.
display_coords = ax.transData.transform((w, a))
figure_coords = fig_inv_trans.transform(display_coords)
figure_coords[1] += box_axes_space
display_coords = fig.transFigure.transform(figure_coords)
ax_coords = ax.transData.inverted().transform(display_coords)
box_loc.append(ax_coords)
return box_loc |
<SYSTEM_TASK:>
Ajdust given boxes so that they don't overlap.
<END_TASK>
<USER_TASK:>
Description:
def adjust_boxes(line_wave, box_widths, left_edge, right_edge,
max_iter=1000, adjust_factor=0.35,
factor_decrement=3.0, fd_p=0.75):
"""Ajdust given boxes so that they don't overlap.
Parameters
----------
line_wave: list or array of floats
Line wave lengths. These are assumed to be the initial y (wave
length) location of the boxes.
box_widths: list or array of floats
Width of box containing labels for each line identification.
left_edge: float
Left edge of valid data i.e., wave length minimum.
right_edge: float
Right edge of valid data i.e., wave lengths maximum.
max_iter: int
Maximum number of iterations to attempt.
adjust_factor: float
Gap between boxes are reduced or increased by this factor after
each iteration.
factor_decrement: float
The `adjust_factor` itself if reduced by this factor, after
certain number of iterations. This is useful for crowded
regions.
fd_p: float
Percentage, given as a fraction between 0 and 1, after which
adjust_factor must be reduced by a factor of
`factor_decrement`. Default is set to 0.75.
Returns
-------
wlp, niter, changed: (float, float, float)
The new y (wave length) location of the text boxes, the number
of iterations used and a flag to indicated whether any changes to
the input locations were made or not.
Notes
-----
This is a direct translation of the code in lineid_plot.pro file in
NASA IDLAstro library.
Positions are returned either when the boxes no longer overlap or
when `max_iter` number of iterations are completed. So if there are
many boxes, there is a possibility that the final box locations
overlap.
References
----------
+ http://idlastro.gsfc.nasa.gov/ftp/pro/plot/lineid_plot.pro
+ http://idlastro.gsfc.nasa.gov/
""" |
# Adjust positions.
niter = 0
changed = True
nlines = len(line_wave)
wlp = line_wave[:]
while changed:
changed = False
for i in range(nlines):
if i > 0:
diff1 = wlp[i] - wlp[i - 1]
separation1 = (box_widths[i] + box_widths[i - 1]) / 2.0
else:
diff1 = wlp[i] - left_edge + box_widths[i] * 1.01
separation1 = box_widths[i]
if i < nlines - 2:
diff2 = wlp[i + 1] - wlp[i]
separation2 = (box_widths[i] + box_widths[i + 1]) / 2.0
else:
diff2 = right_edge + box_widths[i] * 1.01 - wlp[i]
separation2 = box_widths[i]
if diff1 < separation1 or diff2 < separation2:
if wlp[i] == left_edge:
diff1 = 0
if wlp[i] == right_edge:
diff2 = 0
if diff2 > diff1:
wlp[i] = wlp[i] + separation2 * adjust_factor
wlp[i] = wlp[i] if wlp[i] < right_edge else \
right_edge
else:
wlp[i] = wlp[i] - separation1 * adjust_factor
wlp[i] = wlp[i] if wlp[i] > left_edge else \
left_edge
changed = True
niter += 1
if niter == max_iter * fd_p:
adjust_factor /= factor_decrement
if niter >= max_iter:
break
return wlp, changed, niter |
<SYSTEM_TASK:>
Create fig and axes if needed and layout axes in fig.
<END_TASK>
<USER_TASK:>
Description:
def prepare_axes(wave, flux, fig=None, ax_lower=(0.1, 0.1),
ax_dim=(0.85, 0.65)):
"""Create fig and axes if needed and layout axes in fig.""" |
# Axes location in figure.
if not fig:
fig = plt.figure()
ax = fig.add_axes([ax_lower[0], ax_lower[1], ax_dim[0], ax_dim[1]])
ax.plot(wave, flux)
return fig, ax |
<SYSTEM_TASK:>
Return default parameters passed to Axes.annotate to create labels.
<END_TASK>
<USER_TASK:>
Description:
def initial_annotate_kwargs():
"""Return default parameters passed to Axes.annotate to create labels.""" |
return dict(
xycoords="data", textcoords="data",
rotation=90, horizontalalignment="center", verticalalignment="center",
arrowprops=dict(arrowstyle="-", relpos=(0.5, 0.0))
) |
<SYSTEM_TASK:>
Return the 2D field averaged radially w.r.t. the center
<END_TASK>
<USER_TASK:>
Description:
def interpolate_grid(cin, cout, data, fillval=0):
"""Return the 2D field averaged radially w.r.t. the center""" |
if np.iscomplexobj(data):
phase = interpolate_grid(
cin, cout, unwrap.unwrap_phase(np.angle(data)), fillval=0)
ampli = interpolate_grid(cin, cout, np.abs(data), fillval=1)
return ampli * np.exp(1j * phase)
ipol = spinterp.interp2d(x=cin[0], y=cin[1], z=data,
kind="linear",
copy=False,
bounds_error=False,
fill_value=fillval)
return ipol(cout[0], cout[1]) |
<SYSTEM_TASK:>
Field behind a dielectric sphere in the Rytov approximation
<END_TASK>
<USER_TASK:>
Description:
def rytov(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, pixel_size=.5e-6, grid_size=(80, 80),
center=(39.5, 39.5), focus=0, radius_sampling=42):
"""Field behind a dielectric sphere in the Rytov approximation
Parameters
----------
radius: float
Radius of the sphere [m]
sphere_index: float
Refractive index of the sphere
medium_index: float
Refractive index of the surrounding medium
wavelength: float
Vacuum wavelength of the imaging light [m]
pixel_size: float
Pixel size [m]
grid_size: tuple of floats
Resulting image size in x and y [px]
center: tuple of floats
Center position in image coordinates [px]
focus: float
.. versionadded:: 0.5.0
Axial focus position [m] measured from the center of the
sphere in the direction of light propagation.
radius_sampling: int
Number of pixels used to sample the sphere radius when
computing the Rytov field. The default value of 42
pixels is a reasonable number for single-cell analysis.
Returns
-------
qpi: qpimage.QPImage
Quantitative phase data set
""" |
# sample the sphere radius with approximately 42px
# (rounded to next integer pixel size)
samp_mult = radius_sampling * pixel_size / radius
sizex = grid_size[0] * samp_mult
sizey = grid_size[1] * samp_mult
grid_size_sim = [np.int(np.round(sizex)),
np.int(np.round(sizey))]
size_factor = grid_size_sim[0] / grid_size[0]
pixel_size_sim = pixel_size / size_factor
field = sphere_prop_fslice_bessel(radius=radius,
sphere_index=sphere_index,
medium_index=medium_index,
wavelength=wavelength,
pixel_size=pixel_size_sim,
grid_size=grid_size_sim,
lD=focus,
approx="rytov",
zeropad=5,
oversample=1
)
# interpolate field back to original image coordinates
# simulation coordinates
x_sim = (np.arange(grid_size_sim[0]) + .5) * pixel_size_sim
y_sim = (np.arange(grid_size_sim[1]) + .5) * pixel_size_sim
# output coordinates
x = (np.arange(grid_size[0]) + grid_size[0] / 2 - center[0]) * pixel_size
y = (np.arange(grid_size[1]) + grid_size[1] / 2 - center[1]) * pixel_size
# Interpolate resulting field with original extent
field = interpolate_grid(cin=(y_sim, x_sim),
cout=(y, x),
data=field)
meta_data = {"pixel size": pixel_size,
"wavelength": wavelength,
"medium index": medium_index,
"sim center": center,
"sim radius": radius,
"sim index": sphere_index,
"sim model": "rytov",
}
qpi = qpimage.QPImage(data=field, which_data="field",
meta_data=meta_data)
return qpi |
<SYSTEM_TASK:>
With a bit of import magic, we load the given path as a python module,
<END_TASK>
<USER_TASK:>
Description:
def _run_resources_file(path, stack):
"""
With a bit of import magic, we load the given path as a python module,
while providing it access to the given stack under the import name '_context'.
This function returns the module's global dictionary.
""" |
import imp, sys, random, string, copy
class ContextImporter(object):
def find_module(self, fullname, path=None):
if fullname == '_context':
self.path = path
return self
return None
def load_module(self, name):
mod = imp.new_module("_context")
mod.stack = stack
return mod
# Temporarily add the context importer into the meta path
old_meta_path = copy.copy(sys.meta_path)
old_path = copy.copy(sys.path)
# Save the modules list, in order to remove modules loaded after this point
old_sys_modules = sys.modules.keys()
# Run the module
# Prepare import environment
abspath = os.path.abspath(path)
sys.meta_path.append(ContextImporter())
sys.path.append(os.path.dirname(abspath)) # Enable importing files within module's folder
# Perform the importing
srcf = open(abspath, "r")
module_name = ''.join(random.choice(string.digits + string.lowercase) for i in range(16))
srcmodule = imp.load_source("cloudcast._template_" + module_name, abspath, srcf)
srcf.close()
# Restore meta path, modules list and return module
sys.meta_path = old_meta_path
sys.path = old_path
for modname in sys.modules.keys():
if not modname in old_sys_modules:
del sys.modules[modname]
return srcmodule |
<SYSTEM_TASK:>
This function actually fills the stack with definitions coming from a template file
<END_TASK>
<USER_TASK:>
Description:
def load_template_srcmodule(self, stack, path):
"""
This function actually fills the stack with definitions coming from a template file
""" |
srcmodule = _run_resources_file(path, stack)
# Process the loaded module and find the stack elements
elements = self.find_stack_elements(srcmodule)
elements = sorted(elements, key=lambda x: x[:-1])
# Assign a name to each element and add to our dictionaries
for (module_name, el_name, element) in elements:
full_name = self.generate_cfn_name(module_name, el_name)
self.name_stack_element(element, full_name)
self.add_stack_element(element) |
<SYSTEM_TASK:>
Add resource definitions to the given template object
<END_TASK>
<USER_TASK:>
Description:
def dump_to_template_obj(self, stack, t):
"""
Add resource definitions to the given template object
""" |
if len(self.Parameters) > 0:
t['Parameters'] = dict([e.contents(stack) for e in self.Parameters])
if len(self.Mappings) > 0:
t['Mappings'] = dict([e.contents(stack) for e in self.Mappings])
if len(self.Resources) > 0:
t['Resources'] = dict([e.contents(stack) for e in self.Resources])
if len(self.Outputs) > 0:
t['Outputs'] = dict([e.contents(stack) for e in self.Outputs]) |
<SYSTEM_TASK:>
Return a string representation of this CloudFormation template.
<END_TASK>
<USER_TASK:>
Description:
def dump_json(self, pretty=True):
"""
Return a string representation of this CloudFormation template.
""" |
# Build template
t = {}
t['AWSTemplateFormatVersion'] = '2010-09-09'
if self.description is not None:
t['Description'] = self.description
self.elements.dump_to_template_obj(self, t)
return _CustomJSONEncoder(indent=2 if pretty else None,
sort_keys=False).encode(t) |
<SYSTEM_TASK:>
Invoke a function in the mainloop, pass the data back.
<END_TASK>
<USER_TASK:>
Description:
def invoke_in_mainloop(func, *args, **kwargs):
"""
Invoke a function in the mainloop, pass the data back.
""" |
results = queue.Queue()
@gcall
def run():
try:
data = func(*args, **kwargs)
results.put(data)
results.put(None)
except BaseException: # XXX: handle
results.put(None)
results.put(sys.exc_info())
raise
data = results.get()
exception = results.get()
if exception is None:
return data
else:
tp, val, tb = results.get()
raise tp, val, tb |
<SYSTEM_TASK:>
Start the task.
<END_TASK>
<USER_TASK:>
Description:
def start(self, *args, **kwargs):
"""Start the task.
This is:
* not threadsave
* assumed to be called in the gtk mainloop
""" |
args = (self.counter,) + args
thread = threading.Thread(
target=self._work_callback,
args=args, kwargs=kwargs
)
thread.setDaemon(self.daemon)
thread.start() |
<SYSTEM_TASK:>
Convert the specified image instance to RGB mode.
<END_TASK>
<USER_TASK:>
Description:
def convert_image_to_rgb_mode(image, fill_color=(255, 255, 255)):
"""
Convert the specified image instance to RGB mode.
@param image: a Python Library Image (PIL) instance to convert its
pixel format to RGB, discarding the alpha channel.
@param fill_color: color to be used to fill transparent pixels when
discaring the alpha channel. By default, the white color.
@return: a Python Library Image instance with pixel format of RGB.
""" |
if image.mode not in ('RGBA', 'LA'):
return image
# In most cases simply discarding the alpha channel will give
# undesirable result, because transparent pixels also have some
# unpredictable colors. It is much better to fill transparent pixels
# with a specified color.
background_image = Image.new(image.mode[:-1], image.size, fill_color)
background_image.paste(image, image.split()[-1])
return background_image |
<SYSTEM_TASK:>
Generate multiple resolution images of the given image.
<END_TASK>
<USER_TASK:>
Description:
def generate_multiple_pixel_resolutions(image, pixel_resolutions,
filter=Filter.NearestNeighbor,
does_crop=False,
crop_aligment=CropAlignment.center,
match_orientation=False):
"""
Generate multiple resolution images of the given image.
@param image: a Python Library Image (PIL) instance to generate
multiple pixel resolutions from.
@param pixel_resolutions: a list of tuples ``(logical_size, width, height)``
where:
* ``logical_size``: string representation of the image size, such
as, for instance, "thumbnail", "small", "medium", "large".
* ``width``: positive integer corresponding to the number of pixel
columns of the image.
* ``height``: positive integer corresponding to the number of
pixel rows.
@param filter: indicate the filter to use when resizing the image.
@param does_crop: indicate whether to crop each generated images.
@param crop_alignment: if the image needs to be cropped, select which
alignment to use when cropping.
@param match_orientation: indicate whether the given canvas size
should be inverted to match the orientation of the image.
@return: an iterator, known as a generator, that returns a Python
Library Image (PIL) instance each the generator is called.
""" |
for (logical_size, width, height) in \
sorted(pixel_resolutions, key=lambda (l, w, h): w, reverse=True):
yield (logical_size,
resize_image(image, (width, height),
filter=filter,
does_crop=does_crop,
crop_aligment=crop_aligment,
match_orientation=match_orientation)) |
<SYSTEM_TASK:>
Determine the exposure of a photo, which can be under-exposed,
<END_TASK>
<USER_TASK:>
Description:
def get_exposure(image, filters=None):
"""
Determine the exposure of a photo, which can be under-exposed,
normally exposed or over-exposed.
@param image: a Python Library Image (PIL) object to determine the
exposure.
@param filters: a list of ``ColorComponentFilter`` filter or ``None``
to use all the filters.
@return: an ``ExposureStatus`` instance that represents the exposure
of the given PIL object.
""" |
def _get_exposure(histogram):
total = sum(histogram)
range_offset = len(histogram) / 4
dark = float(sum(histogram[0:range_offset])) / total
#normal = float(sum(histogram[range_offset:-range_offset])) / total
light = float(sum(histogram[-range_offset:])) / total
return PictureExposure.UnderExposed if dark > 0.5 and light < 0.5 \
else PictureExposure.OverExposed if dark < 0.5 and light > 0.5 \
else PictureExposure.NormallyExposed
FILTER_SETTINGS = {
ColorComponentFilter.Red: ('RGB', 0, 256),
ColorComponentFilter.Green: ('RGB', 256, 512),
ColorComponentFilter.Blue: ('RGB', 512, 768),
ColorComponentFilter.Grey: ('L', 0, 256)
}
exposures = collections.defaultdict(int)
for exposure in [ _get_exposure(image.convert(mode).histogram()[start_index:end_index])
for (mode, start_index, end_index) in [ FILTER_SETTINGS[filtr]
for filtr in filters or [
ColorComponentFilter.Red,
ColorComponentFilter.Green,
ColorComponentFilter.Blue,
ColorComponentFilter.Grey
] ] ]:
exposures[exposure] += 1
return sorted(exposures.iterkeys(), key=lambda k: exposures[k], reverse=True)[0] |
<SYSTEM_TASK:>
Indicate whether the specified image file is valid or not.
<END_TASK>
<USER_TASK:>
Description:
def is_image_file_valid(file_path_name):
"""
Indicate whether the specified image file is valid or not.
@param file_path_name: absolute path and file name of an image.
@return: ``True`` if the image file is valid, ``False`` if the file is
truncated or does not correspond to a supported image.
""" |
# Image.verify is only implemented for PNG images, and it only verifies
# the CRC checksum in the image. The only way to check from within
# Pillow is to load the image in a try/except and check the error. If
# as much info as possible is from the image is needed,
# ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it
# will attempt to parse as much as possible.
try:
with Image.open(file_path_name) as image:
image.load()
except IOError:
return False
return True |
<SYSTEM_TASK:>
Load the image from the specified file and orient the image accordingly
<END_TASK>
<USER_TASK:>
Description:
def open_and_reorient_image(handle):
"""
Load the image from the specified file and orient the image accordingly
to the Exif tag that the file might embed, which would indicate the
orientation of the camera relative to the captured scene.
@param handle: a Python file object.
@return: an instance returned by the Python Library Image library.
""" |
# Retrieve tags from the Exchangeable image file format (Exif)
# included in the picture. If the orientation of the picture is not
# top left side, rotate it accordingly.
# @deprecated
# exif_tags = dict([ (exif_tag.tag, exif_tag)
# for exif_tag in exif.process_file(handle).itervalues()
# if hasattr(exif_tag, 'tag') ])
exif_tags = exifread.process_file(handle)
exif_tag_orientation = exif_tags.get(EXIF_TAG_ORIENTATION)
rotation_angle = exif_tag_orientation and {
3L: 180,
6L: 270,
8L: 90
}.get(exif_tag_orientation.values[0])
handle.seek(0) # exif.process_file has updated the file's current position.
image = Image.open(handle)
return image if rotation_angle is None else image.rotate(rotation_angle) |
<SYSTEM_TASK:>
Realign the given image providing the specific horizontal and vertical
<END_TASK>
<USER_TASK:>
Description:
def realign_image(image, shift_x, shift_y, max_shift_x, max_shift_y,
shift_angle=0.0, filter=Filter.NearestNeighbor,
stretch_factor=None,
cropping_box=None):
"""
Realign the given image providing the specific horizontal and vertical
shifts, and crop the image providing the maximum horizontal and
vertical shifts of images of a same set so that they all have the same
size.
@param image: an instance of Python Image Library (PIL) image.
@param shift_x: horizontal shift in pixels of the image.
@param shift_y: vertical shift in pixels of the image.
@param max_shift_x: maximum absolute value of the horizontal shift in
pixels of the images in the capture.
@param max_shift_y: maximum absolute value of the vertical shift in
pixels of the images in the capture.
@param shift_angle: horizontal displacement angle in degrees of
the image.
@param filter: indicate the filter to use when rotating the image.
@param stretch_factor: coefficient of multiplication to stretch or
to shrink the image in both horizontal and vertical
directions.
@param cropping_box: a 4-tuple defining the left, upper, right, and
lower pixel coordinate of the rectangular region from the
specified image.
@return: a new instance of Python Image Library (PIL) image.
""" |
(width, height) = image.size
# Determine the new size of the image based on the maximal horizontal
# and vertical shifts of all the other images in this series.
new_width = width - max_shift_x * 2
new_height = height - max_shift_y * 2
# Determine the coordinates of the zone to crop to center the image
# based on the horizontal and vertical shifts.
bounding_box_x = (0 if shift_x < 0 else shift_x * 2)
bounding_box_y = (0 if shift_y < 0 else shift_y * 2)
if max_shift_x > shift_x:
bounding_box_width = width - abs(shift_x) * 2
bounding_box_x += (bounding_box_width - new_width) / 2
#bounding_box_x = max_shift_x - abs(shift_x)
if max_shift_y > shift_y:
bounding_box_height = height - abs(shift_y) * 2
bounding_box_y += (bounding_box_height - new_height) / 2
#bounding_box_y = max_shift_y - abs(shift_y)
# Crop the image and rotate it based on the horizontal displacement
# angle of this image.
image = image.crop((bounding_box_x, bounding_box_y,
bounding_box_x + new_width, bounding_box_y + new_height)) \
.rotate(-shift_angle, PIL_FILTER_MAP[filter])
# Stretch or shrink this image based on its coefficient, keeping the
# calculated new size of this image.
if stretch_factor and stretch_factor > 0:
image = image.resize((int(round(width * stretch_factor)), int(round(height * stretch_factor))),
PIL_FILTER_MAP[filter])
(width, height) = image.size
if stretch_factor >= 1:
image = image.crop(((width - new_width) / 2, (height - new_height) / 2,
(width - new_width) / 2 + new_width - 1, (height - new_height) / 2 + new_height - 1))
else:
_image = Image.new(image.mode, (new_width, new_height))
_image.paste(image, ((new_width - width) / 2, (new_height - height) / 2))
image = _image
# Crop the image to the specified rectangle, if any defined.
if cropping_box:
(crop_x1, crop_y1, crop_x2, crop_y2) = cropping_box
(width, height) = image.size
image = image.crop(
(int(round(crop_x1 * width)), int(round(crop_y1 * height)),
int(round(crop_x2 * width)), int(round(crop_y2 * height))))
return image |
<SYSTEM_TASK:>
Resize the specified image to the required dimension.
<END_TASK>
<USER_TASK:>
Description:
def resize_image(image, canvas_size,
filter=Filter.NearestNeighbor,
does_crop=False,
crop_aligment=CropAlignment.center,
crop_form=CropForm.rectangle,
match_orientation=False):
"""
Resize the specified image to the required dimension.
@param image: a Python Image Library (PIL) image instance.
@param canvas_size: requested size in pixels, as a 2-tuple
``(width, height)``.
@param filter: indicate the filter to use when resizing the image.
@param does_crop: indicate whether the image needs to be cropped.
@param crop_alignment: if the image needs to be cropped, select which
alignment to use when cropping.
@param match_orientation: indicate whether the given canvas size
should be inverted to match the orientation of the image.
@return: a PIL image instance corresponding to the image that has been
resized, and possibly cropped.
""" |
(source_width, source_height) = image.size
source_aspect = source_width / float(source_height)
(canvas_width, canvas_height) = canvas_size
canvas_aspect = canvas_width / float(canvas_height)
if match_orientation:
if (source_aspect > 1.0 > canvas_aspect) or (source_aspect < 1.0 < canvas_aspect):
(canvas_width, canvas_height) = (canvas_height, canvas_width)
canvas_aspect = canvas_width / float(canvas_height)
if does_crop:
if source_aspect > canvas_aspect:
destination_width = int(source_height * canvas_aspect)
offset = 0 if crop_aligment == CropAlignment.left_or_top \
else source_width - destination_width if crop_aligment == CropAlignment.right_or_bottom \
else (source_width - destination_width) / 2
box = (offset, 0, offset + destination_width, source_height)
else:
destination_height = int(source_width / canvas_aspect)
offset = 0 if crop_aligment == CropAlignment.left_or_top \
else source_height - destination_height if crop_aligment == CropAlignment.right_or_bottom \
else (source_height - destination_height) / 2
box = (0, offset, source_width, destination_height + offset)
else:
if canvas_aspect > source_aspect:
# The canvas aspect is greater than the image aspect when the canvas's
# width is greater than the image's width, in which case we need to
# crop the left and right edges of the image.
destination_width = int(canvas_aspect * source_height)
offset = (source_width - destination_width) / 2
box = (offset, 0, source_width - offset, source_height)
else:
# The image aspect is greater than the canvas aspect when the image's
# width is greater than the canvas's width, in which case we need to
# crop the top and bottom edges of the image.
destination_height = int(source_width / canvas_aspect)
offset = (source_height - destination_height) / 2
box = (0, offset, source_width, source_height - offset)
return image.crop(box).resize((canvas_width, canvas_height), PIL_FILTER_MAP[filter]) |
<SYSTEM_TASK:>
Fit the angles to the model
<END_TASK>
<USER_TASK:>
Description:
def __get_vtt_angles(self, pvals, nvals):
""" Fit the angles to the model
Args:
pvals (array-like) : positive values
nvals (array-like) : negative values
Returns: normalized coef_ values
""" |
# https://www.khanacademy.org/math/trigonometry/unit-circle-trig-func/inverse_trig_functions/v/inverse-trig-functions--arctan
angles = np.arctan2(pvals, nvals)-np.pi/4
norm = np.maximum(np.minimum(angles, np.pi-angles), -1*np.pi-angles)
norm = csr_matrix(norm)
# Remove any weight from the NER features. These will be added later.
for key, value in self.B.items():
norm[0, key] = 0.
return norm |
<SYSTEM_TASK:>
Set the parameters of the estimator.
<END_TASK>
<USER_TASK:>
Description:
def set_params(self, **params):
""" Set the parameters of the estimator.
Args:
bias (array-like) : bias of the estimator. Also known as the intercept in a linear model.
weights (array-like) : weights of the features. Also known as coeficients.
NER biases (array-like) : NER entities infering column position on X and bias value. Ex: `b_4=10, b_5=6`.
Example:
>>> cls = VTT()
>>> cls.set_params(b_4=10, b_5=6, b_6=8)
""" |
if 'bias' in params.keys():
self.intercept_ = params['bias']
if 'weights' in params.keys():
self.coef_ = params['weights']
for key in params.keys():
if 'b_' == key[:2]:
self.B[int(key[2:])] = params[key]
return self |
<SYSTEM_TASK:>
Get parameters for the estimator.
<END_TASK>
<USER_TASK:>
Description:
def get_params(self, deep=True):
""" Get parameters for the estimator.
Args:
deep (boolean, optional) : If True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns:
params : mapping of string to any contained subobjects that are estimators.
""" |
params = {'weights':self.coef_, 'bias':self.intercept_}
if deep:
for key, value in self.B.items():
params['b_'+str(key)] = value
return params |
<SYSTEM_TASK:>
Send a electronic mail to a list of recipients.
<END_TASK>
<USER_TASK:>
Description:
def send_email(hostname, username, password,
author_name, author_email_address, recipient_email_addresses,
subject, content,
file_path_names=None,
port_number=587,
unsubscribe_mailto_link=None,
unsubscribe_url=None):
"""
Send a electronic mail to a list of recipients.
@note: Outlook and Gmail leverage the list-unsubscribe option for
senders with good sending reputations:
"In order to receive unsubscribe feedback, senders must include an
RFC2369-compliant List-Unsubscribe header containing a mailto: address.
Please note that we only enable this feedback via email, so URIs for
other protocols such as http will be ignored. The sender must also
have a good reputation, and must act promptly in removing users from
their lists. We do not provide unsubscribe feedback to senders when a
user unsubscribes from an untrusted message."
[https://sendersupport.olc.protection.outlook.com/pm/junkemail.aspx]
"This only works for some senders right now. We're actively encouraging
senders to support auto-unsubscribe — we think 100% should. We won't
provide the unsubscribe option on messages from spammers: we can't
trust that they'll actually unsubscribe you, and they might even send
you more spam. So you'll only see the unsubscribe option for senders
that we're pretty sure are not spammers and will actually honor your
unsubscribe request. We're being pretty conservative about which
senders to trust in the beginning; over time, we hope to offer the
ability to unsubscribe from more email."
[https://gmail.googleblog.com/2009/07/unsubscribing-made-easy.html]
@param hostname: Internet address or fully qualified domain name --
human-readable nickname that corresponds to the address -- of the
SMTP server is running on.
@param username: username to authenticate with against the SMTP server.
@param password: password associate to the username to authenticate
with against the SMTP server.
@param author_name: complete name of the originator of the message.
@param author_email_address: address of the mailbox to which the author
of the message suggests that replies be sent.
@param recipient_email_addresses: email address(es) of the primary
recipient(s) of the message. A bare string will be treated as a
list with one address.
@param subject: a short string identifying the topic of the message.
@param content: the body of the message.
@param file_path_names: a list of complete fully qualified path name
(FQPN) of the files to attach to this message.
@param port_number: Internet port number on which the remote SMTP
server is listening at.
SMTP communication between mail servers uses TCP port 25. Mail
clients on the other hand, often submit the outgoing emails to a mail
server on port 587. Despite being deprecated, mail providers
sometimes still permit the use of nonstandard port 465 for this
purpose.
@param unsubscribe_mailto_link: an email address to directly
unsubscribe the recipient who requests to be removed from the
mailing list (https://tools.ietf.org/html/rfc2369.html).
In addition to the email address, other information can be provided.
In fact, any standard mail header fields can be added to the mailto
link. The most commonly used of these are "subject", "cc", and "body"
(which is not a true header field, but allows you to specify a short
content message for the new email). Each field and its value is
specified as a query term (https://tools.ietf.org/html/rfc6068).
@param unsubscribe_url: a link that will take the subscriber to a
landing page to process the unsubscribe request. This can be a
subscription center, or the subscriber is removed from the list
right away and gets sent to a landing page that confirms the
unsubscribe.
""" |
# Convert bare string representing only one email address as a list with
# this single email address.
if not isinstance(recipient_email_addresses, (list, set, tuple)):
recipient_email_addresses = [ recipient_email_addresses ]
# Build the message to be sent.
message = MIMEMultipart()
message['From'] = __build_author_name_expr(author_name, author_email_address)
message['To'] = COMMASPACE.join(recipient_email_addresses)
message['Date'] = formatdate(localtime=True)
message['Subject'] = subject
if author_email_address:
message.add_header('Reply-To', author_email_address)
# Add method(s) to unsubscribe a recipient from a mailing list at his
# request.
if unsubscribe_mailto_link or unsubscribe_url:
unsubscribe_methods = [
unsubscribe_url and '<%s>' % unsubscribe_url,
unsubscribe_mailto_link and '<mailto:%s>' % unsubscribe_mailto_link,
]
message.add_header('List-Unsubscribe', ', '.join([ method for method in unsubscribe_methods if method ]))
# Detect whether the content of the message is a plain text or an HTML
# content, based on whether the content starts with "<" or not.
message.attach(MIMEText(content.encode('utf-8'),
_charset='utf-8',
_subtype='html' if content and content.strip()[0] == '<' else 'plain'))
# Attache the specified files to the message.
for file_path_name in file_path_names or []:
part = MIMEBase('application', 'octet-stream')
with open(file_path_name, 'rb') as handle:
part.set_payload(handle.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_path_name))
message.attach(part)
# Connect the remote mail server and send the message.
smtp_server = smtplib.SMTP_SSL(hostname) if port_number == 465 else smtplib.SMTP(hostname, port_number)
smtp_server.ehlo()
if port_number <> 465:
smtp_server.starttls()
smtp_server.ehlo()
smtp_server.login(username, password)
smtp_server.sendmail(author_email_address, recipient_email_addresses, message.as_string())
smtp_server.close() |
<SYSTEM_TASK:>
Confirm that a send has completed. Does not actually check confirmations,
<END_TASK>
<USER_TASK:>
Description:
def confirm_send(address, amount, ref_id=None, session=ses):
"""
Confirm that a send has completed. Does not actually check confirmations,
but instead assumes that if this is called, the transaction has been
completed. This is because we assume our own sends are safe.
:param session:
:param str ref_id: The updated ref_id for the transaction in question
:param str address: The address that was sent to
:param Amount amount: The amount that was sent
""" |
debitq = session.query(wm.Debit)
debitq = debitq.filter(wm.Debit.address == address)
debitq = debitq.filter(wm.Debit.amount == amount)
debit = debitq.filter(wm.Debit.transaction_state == 'unconfirmed').first()
if not debit:
raise ValueError("Debit already confirmed or address unknown.")
debit.transaction_state = 'complete'
if ref_id is not None:
debit.ref_id = ref_id
session.add(debit)
session.commit()
return debit |
<SYSTEM_TASK:>
Read a configuration from disk.
<END_TASK>
<USER_TASK:>
Description:
def read_config(path):
"""
Read a configuration from disk.
Arguments
path -- the loation to deserialize
""" |
parser = _make_parser()
if parser.read(path):
return parser
raise Exception("Failed to read {}".format(path)) |
<SYSTEM_TASK:>
Inverse correction of refractive index and radius for Rytov
<END_TASK>
<USER_TASK:>
Description:
def correct_rytov_sc_input(radius_sc, sphere_index_sc, medium_index,
radius_sampling):
"""Inverse correction of refractive index and radius for Rytov
This method returns the inverse of :func:`correct_rytov_output`.
Parameters
----------
radius_sc: float
Systematically corrected radius of the sphere [m]
sphere_index_sc: float
Systematically corrected refractive index of the sphere
medium_index: float
Refractive index of the surrounding medium
radius_sampling: int
Number of pixels used to sample the sphere radius when
computing the Rytov field.
Returns
-------
radius: float
Fitted radius of the sphere [m]
sphere_index: float
Fitted refractive index of the sphere
See Also
--------
correct_rytov_output: the inverse of this method
""" |
params = get_params(radius_sampling)
# sage script:
# var('sphere_index, sphere_index_sc, na, nb, medium_index')
# x = sphere_index / medium_index - 1
# eq = sphere_index_sc == sphere_index + ( na*x^2 + nb*x) * medium_index
# solve([eq], [sphere_index])
# (take the positive sign solution)
na = params["na"]
nb = params["nb"]
prefac = medium_index / (2 * na)
sm = 2 * na - nb - 1
rt = nb**2 - 4 * na + 2 * nb + 1 + 4 / medium_index * na * sphere_index_sc
sphere_index = prefac * (sm + np.sqrt(rt))
x = sphere_index / medium_index - 1
radius = radius_sc / (params["ra"] * x**2
+ params["rb"] * x
+ params["rc"])
return radius, sphere_index |
<SYSTEM_TASK:>
r"""Error-correction of refractive index and radius for Rytov
<END_TASK>
<USER_TASK:>
Description:
def correct_rytov_output(radius, sphere_index, medium_index, radius_sampling):
r"""Error-correction of refractive index and radius for Rytov
This method corrects the fitting results for `radius`
:math:`r_\text{Ryt}` and `sphere_index` :math:`n_\text{Ryt}`
obtained using :func:`qpsphere.models.rytov` using
the approach described in :cite:`Mueller2018` (eqns. 3,4, and 5).
.. math::
n_\text{Ryt-SC} &= n_\text{Ryt} + n_\text{med} \cdot
\left( a_n x^2 + b_n x + c_n \right)
r_\text{Ryt-SC} &= r_\text{Ryt} \cdot
\left( a_r x^2 +b_r x + c_r \right)
&\text{with} x = \frac{n_\text{Ryt}}{n_\text{med}} - 1
The correction factors are given in
:data:`qpsphere.models.mod_rytov_sc.RSC_PARAMS`.
Parameters
----------
radius: float
Fitted radius of the sphere :math:`r_\text{Ryt}` [m]
sphere_index: float
Fitted refractive index of the sphere :math:`n_\text{Ryt}`
medium_index: float
Refractive index of the surrounding medium :math:`n_\text{med}`
radius_sampling: int
Number of pixels used to sample the sphere radius when
computing the Rytov field.
Returns
-------
radius_sc: float
Systematically corrected radius of the sphere
:math:`r_\text{Ryt-SC}` [m]
sphere_index_sc: float
Systematically corrected refractive index of the sphere
:math:`n_\text{Ryt-SC}`
See Also
--------
correct_rytov_sc_input: the inverse of this method
""" |
params = get_params(radius_sampling)
x = sphere_index / medium_index - 1
radius_sc = radius * (params["ra"] * x**2
+ params["rb"] * x
+ params["rc"])
sphere_index_sc = sphere_index + medium_index * (params["na"] * x**2
+ params["nb"] * x)
return radius_sc, sphere_index_sc |
<SYSTEM_TASK:>
r"""Field behind a dielectric sphere, systematically corrected Rytov
<END_TASK>
<USER_TASK:>
Description:
def rytov_sc(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80),
center=(39.5, 39.5), radius_sampling=42):
r"""Field behind a dielectric sphere, systematically corrected Rytov
This method implements a correction of
:func:`qpsphere.models.rytov`, where the
`radius` :math:`r_\text{Ryt}` and the `sphere_index`
:math:`n_\text{Ryt}` are corrected using
the approach described in :cite:`Mueller2018` (eqns. 3,4, and 5).
.. math::
n_\text{Ryt-SC} &= n_\text{Ryt} + n_\text{med} \cdot
\left( a_n x^2 + b_n x + c_n \right)
r_\text{Ryt-SC} &= r_\text{Ryt} \cdot
\left( a_r x^2 +b_r x + c_r \right)
&\text{with} x = \frac{n_\text{Ryt}}{n_\text{med}} - 1
The correction factors are given in
:data:`qpsphere.models.mod_rytov_sc.RSC_PARAMS`.
Parameters
----------
radius: float
Radius of the sphere [m]
sphere_index: float
Refractive index of the sphere
medium_index: float
Refractive index of the surrounding medium
wavelength: float
Vacuum wavelength of the imaging light [m]
pixel_size: float
Pixel size [m]
grid_size: tuple of floats
Resulting image size in x and y [px]
center: tuple of floats
Center position in image coordinates [px]
radius_sampling: int
Number of pixels used to sample the sphere radius when
computing the Rytov field. The default value of 42
pixels is a reasonable number for single-cell analysis.
Returns
-------
qpi: qpimage.QPImage
Quantitative phase data set
""" |
r_ryt, n_ryt = correct_rytov_sc_input(radius_sc=radius,
sphere_index_sc=sphere_index,
medium_index=medium_index,
radius_sampling=radius_sampling)
qpi = mod_rytov.rytov(radius=r_ryt,
sphere_index=n_ryt,
medium_index=medium_index,
wavelength=wavelength,
pixel_size=pixel_size,
grid_size=grid_size,
center=center,
radius_sampling=radius_sampling)
# update correct simulation parameters
qpi["sim radius"] = radius
qpi["sim index"] = sphere_index
qpi["sim model"] = "rytov-sc"
return qpi |
<SYSTEM_TASK:>
Add a GObject signal to the current object.
<END_TASK>
<USER_TASK:>
Description:
def gsignal(name, *args, **kwargs):
"""Add a GObject signal to the current object.
It current supports the following types:
- str, int, float, long, object, enum
:param name: name of the signal
:param args: types for signal parameters,
if the first one is a string 'override', the signal will be
overridden and must therefor exists in the parent GObject.
.. note:: flags: A combination of;
- gobject.SIGNAL_RUN_FIRST
- gobject.SIGNAL_RUN_LAST
- gobject.SIGNAL_RUN_CLEANUP
- gobject.SIGNAL_NO_RECURSE
- gobject.SIGNAL_DETAILED
- gobject.SIGNAL_ACTION
- gobject.SIGNAL_NO_HOOKS
""" |
frame = sys._getframe(1)
try:
locals = frame.f_locals
finally:
del frame
dict = locals.setdefault('__gsignals__', {})
if args and args[0] == 'override':
dict[name] = 'override'
else:
retval = kwargs.get('retval', None)
if retval is None:
default_flags = gobject.SIGNAL_RUN_FIRST
else:
default_flags = gobject.SIGNAL_RUN_LAST
flags = kwargs.get('flags', default_flags)
if retval is not None and flags != gobject.SIGNAL_RUN_LAST:
raise TypeError(
"You cannot use a return value without setting flags to "
"gobject.SIGNAL_RUN_LAST")
dict[name] = (flags, retval, args) |
<SYSTEM_TASK:>
Add a GObject property to the current object.
<END_TASK>
<USER_TASK:>
Description:
def gproperty(name, ptype, default=None, nick='', blurb='',
flags=gobject.PARAM_READWRITE, **kwargs):
"""Add a GObject property to the current object.
:param name: name of property
:param ptype: type of property
:param default: default value
:param nick: short description
:param blurb: long description
:param flags: parameter flags, a combination of:
- PARAM_READABLE
- PARAM_READWRITE
- PARAM_WRITABLE
- PARAM_CONSTRUCT
- PARAM_CONSTRUCT_ONLY
- PARAM_LAX_VALIDATION
Optional, only for int, float, long types:
:param minimum: minimum allowed value
:param: maximum: maximum allowed value
""" |
# General type checking
if default is None:
default = _DEFAULT_VALUES.get(ptype)
elif not isinstance(default, ptype):
raise TypeError("default must be of type %s, not %r" % (
ptype, default))
if not isinstance(nick, str):
raise TypeError('nick for property %s must be a string, not %r' % (
name, nick))
nick = nick or name
if not isinstance(blurb, str):
raise TypeError('blurb for property %s must be a string, not %r' % (
name, blurb))
# Specific type checking
if ptype == int or ptype == float or ptype == long:
default = (kwargs.get('minimum', ptype(0)),
kwargs.get('maximum', _MAX_VALUES[ptype]),
default)
elif ptype == bool:
if default is not True and default is not False:
raise TypeError("default must be True or False, not %r" % default)
default = default,
elif gobject.type_is_a(ptype, gobject.GEnum):
if default is None:
raise TypeError("enum properties needs a default value")
elif not isinstance(default, ptype):
raise TypeError("enum value %s must be an instance of %r" %
(default, ptype))
default = default,
elif ptype == str:
default = default,
elif ptype == object:
if default is not None:
raise TypeError("object types does not have default values")
default = ()
else:
raise NotImplementedError("type %r" % ptype)
if flags < 0 or flags > 32:
raise TypeError("invalid flag value: %r" % (flags,))
frame = sys._getframe(1)
try:
locals = frame.f_locals
dict = locals.setdefault('__gproperties__', {})
finally:
del frame
dict[name] = (ptype, nick, blurb) + default + (flags,) |
<SYSTEM_TASK:>
Use up all the events waiting to be run
<END_TASK>
<USER_TASK:>
Description:
def refresh_gui(delay=0.0001, wait=0.0001):
"""Use up all the events waiting to be run
:param delay: Time to wait before using events
:param wait: Time to wait between iterations of events
This function will block until all pending events are emitted. This is
useful in testing to ensure signals and other asynchronous functionality
is required to take place.
""" |
time.sleep(delay)
while gtk.events_pending():
gtk.main_iteration_do(block=False)
time.sleep(wait) |
<SYSTEM_TASK:>
Run a widget, or a delegate in a Window
<END_TASK>
<USER_TASK:>
Description:
def run_in_window(target, on_destroy=gtk.main_quit):
"""Run a widget, or a delegate in a Window
""" |
w = _get_in_window(target)
if on_destroy:
w.connect('destroy', on_destroy)
w.resize(500, 400)
w.move(100, 100)
w.show_all()
gtk.main() |
<SYSTEM_TASK:>
Detect the type of the terminal.
<END_TASK>
<USER_TASK:>
Description:
def _detect_term_type():
"""
Detect the type of the terminal.
""" |
if os.name == 'nt':
if os.environ.get('TERM') == 'xterm':
# maybe MinTTY
return 'mintty'
else:
return 'nt'
if platform.system().upper().startswith('CYGWIN'):
return 'cygwin'
return 'posix' |
<SYSTEM_TASK:>
Clear the terminal screen.
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
"""
Clear the terminal screen.
""" |
if hasattr(self.stdout, 'isatty') and self.stdout.isatty() or self.term_type == 'mintty':
cmd, shell = {
'posix': ('clear', False),
'nt': ('cls', True),
'cygwin': (['echo', '-en', r'\ec'], False),
'mintty': (r'echo -en "\ec', False),
}[self.term_type]
subprocess.call(cmd, shell=shell, stdin=self.stdin, stdout=self.stdout, stderr=self.stderr) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.