text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Makes a texture consisting of a grid of vertical and horizontal lines.
<END_TASK>
<USER_TASK:>
Description:
def make_grid_texture(num_h_lines=10, num_v_lines=10, resolution=50):
"""Makes a texture consisting of a grid of vertical and horizontal lines.
Args:
num_h_lines (int): the number of horizontal lines to draw
num_v_lines (int): the number of vertical lines to draw
resolution (int): the number of midpoints to draw on each line
Returns:
A texture.
""" |
x_h, y_h = make_lines_texture(num_h_lines, resolution)
y_v, x_v = make_lines_texture(num_v_lines, resolution)
return np.concatenate([x_h, x_v]), np.concatenate([y_h, y_v]) |
<SYSTEM_TASK:>
Makes a texture consisting of a spiral from the origin.
<END_TASK>
<USER_TASK:>
Description:
def make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000):
"""Makes a texture consisting of a spiral from the origin.
Args:
spirals (float): the number of rotations to make
ccw (bool): make spirals counter-clockwise (default is clockwise)
offset (float): if non-zero, spirals start offset by this amount
resolution (int): number of midpoints along the spiral
Returns:
A texture.
""" |
dist = np.sqrt(np.linspace(0., 1., resolution))
if ccw:
direction = 1.
else:
direction = -1.
angle = dist * spirals * np.pi * 2. * direction
spiral_texture = (
(np.cos(angle) * dist / 2.) + 0.5,
(np.sin(angle) * dist / 2.) + 0.5
)
return spiral_texture |
<SYSTEM_TASK:>
Makes a texture consisting on a grid of hexagons.
<END_TASK>
<USER_TASK:>
Description:
def make_hex_texture(grid_size = 2, resolution=1):
"""Makes a texture consisting on a grid of hexagons.
Args:
grid_size (int): the number of hexagons along each dimension of the grid
resolution (int): the number of midpoints along the line of each hexagon
Returns:
A texture.
""" |
grid_x, grid_y = np.meshgrid(
np.arange(grid_size),
np.arange(grid_size)
)
ROOT_3_OVER_2 = np.sqrt(3) / 2
ONE_HALF = 0.5
grid_x = (grid_x * np.sqrt(3) + (grid_y % 2) * ROOT_3_OVER_2).flatten()
grid_y = grid_y.flatten() * 1.5
grid_points = grid_x.shape[0]
x_offsets = np.interp(np.arange(4 * resolution),
np.arange(4) * resolution, [
ROOT_3_OVER_2,
0.,
-ROOT_3_OVER_2,
-ROOT_3_OVER_2,
])
y_offsets = np.interp(np.arange(4 * resolution),
np.arange(4) * resolution, [
-ONE_HALF,
-1.,
-ONE_HALF,
ONE_HALF
])
tmx = 4 * resolution
x_t = np.tile(grid_x, (tmx, 1)) + x_offsets.reshape((tmx, 1))
y_t = np.tile(grid_y, (tmx, 1)) + y_offsets.reshape((tmx, 1))
x_t = np.vstack([x_t, np.tile(np.nan, (1, grid_x.size))])
y_t = np.vstack([y_t, np.tile(np.nan, (1, grid_y.size))])
return fit_texture((x_t.flatten('F'), y_t.flatten('F'))) |
<SYSTEM_TASK:>
Makes a surface by generating random noise and blurring it.
<END_TASK>
<USER_TASK:>
Description:
def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None):
"""Makes a surface by generating random noise and blurring it.
Args:
dims (pair): the dimensions of the surface to create
blur (float): the amount of Gaussian blur to apply
seed (int): a random seed to use (optional)
Returns:
surface: A surface.
""" |
if seed is not None:
np.random.seed(seed)
return gaussian_filter(np.random.normal(size=dims), blur) |
<SYSTEM_TASK:>
Makes a pair of gradients to generate textures from numpy primitives.
<END_TASK>
<USER_TASK:>
Description:
def make_gradients(dims=DEFAULT_DIMS):
"""Makes a pair of gradients to generate textures from numpy primitives.
Args:
dims (pair): the dimensions of the surface to create
Returns:
pair: A pair of surfaces.
""" |
return np.meshgrid(
np.linspace(0.0, 1.0, dims[0]),
np.linspace(0.0, 1.0, dims[1])
) |
<SYSTEM_TASK:>
Makes a surface from the 3D sine function.
<END_TASK>
<USER_TASK:>
Description:
def make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0):
"""Makes a surface from the 3D sine function.
Args:
dims (pair): the dimensions of the surface to create
offset (float): an offset applied to the function
scale (float): a scale applied to the sine frequency
Returns:
surface: A surface.
""" |
gradients = (np.array(make_gradients(dims)) - offset) * scale * np.pi
return np.sin(np.linalg.norm(gradients, axis=0)) |
<SYSTEM_TASK:>
Makes a surface from the product of sine functions on each axis.
<END_TASK>
<USER_TASK:>
Description:
def make_bubble_surface(dims=DEFAULT_DIMS, repeat=3):
"""Makes a surface from the product of sine functions on each axis.
Args:
dims (pair): the dimensions of the surface to create
repeat (int): the frequency of the waves is set to ensure this many
repetitions of the function
Returns:
surface: A surface.
""" |
gradients = make_gradients(dims)
return (
np.sin((gradients[0] - 0.5) * repeat * np.pi) *
np.sin((gradients[1] - 0.5) * repeat * np.pi)) |
<SYSTEM_TASK:>
Initialize a controller.
<END_TASK>
<USER_TASK:>
Description:
def init_controller(url):
"""Initialize a controller.
Provides a single global controller for applications that can't do this
themselves
""" |
# pylint: disable=global-statement
global _VERA_CONTROLLER
created = False
if _VERA_CONTROLLER is None:
_VERA_CONTROLLER = VeraController(url)
created = True
_VERA_CONTROLLER.start()
return [_VERA_CONTROLLER, created] |
<SYSTEM_TASK:>
Perform a data_request and return the result.
<END_TASK>
<USER_TASK:>
Description:
def data_request(self, payload, timeout=TIMEOUT):
"""Perform a data_request and return the result.""" |
request_url = self.base_url + "/data_request"
return requests.get(request_url, timeout=timeout, params=payload) |
<SYSTEM_TASK:>
Get basic device info from Vera.
<END_TASK>
<USER_TASK:>
Description:
def get_simple_devices_info(self):
"""Get basic device info from Vera.""" |
j = self.data_request({'id': 'sdata'}).json()
self.scenes = []
items = j.get('scenes')
for item in items:
self.scenes.append(VeraScene(item, self))
if j.get('temperature'):
self.temperature_units = j.get('temperature')
self.categories = {}
cats = j.get('categories')
for cat in cats:
self.categories[cat.get('id')] = cat.get('name')
self.device_id_map = {}
devs = j.get('devices')
for dev in devs:
dev['categoryName'] = self.categories.get(dev.get('category'))
self.device_id_map[dev.get('id')] = dev |
<SYSTEM_TASK:>
Search the list of connected devices by name.
<END_TASK>
<USER_TASK:>
Description:
def get_device_by_name(self, device_name):
"""Search the list of connected devices by name.
device_name param is the string name of the device
""" |
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if device.name == device_name:
found_device = device
# found the first (and should be only) one so we will finish
break
if found_device is None:
logger.debug('Did not find device with {}'.format(device_name))
return found_device |
<SYSTEM_TASK:>
Search the list of connected devices by ID.
<END_TASK>
<USER_TASK:>
Description:
def get_device_by_id(self, device_id):
"""Search the list of connected devices by ID.
device_id param is the integer ID of the device
""" |
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if device.device_id == device_id:
found_device = device
# found the first (and should be only) one so we will finish
break
if found_device is None:
logger.debug('Did not find device with {}'.format(device_id))
return found_device |
<SYSTEM_TASK:>
Get list of connected devices.
<END_TASK>
<USER_TASK:>
Description:
def get_devices(self, category_filter=''):
"""Get list of connected devices.
category_filter param is an array of strings
""" |
# pylint: disable=too-many-branches
# the Vera rest API is a bit rough so we need to make 2 calls to get
# all the info e need
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
self.devices = []
items = j.get('devices')
for item in items:
item['deviceInfo'] = self.device_id_map.get(item.get('id'))
if item.get('deviceInfo'):
device_category = item.get('deviceInfo').get('category')
if device_category == CATEGORY_DIMMER:
device = VeraDimmer(item, self)
elif ( device_category == CATEGORY_SWITCH or
device_category == CATEGORY_VERA_SIREN):
device = VeraSwitch(item, self)
elif device_category == CATEGORY_THERMOSTAT:
device = VeraThermostat(item, self)
elif device_category == CATEGORY_LOCK:
device = VeraLock(item, self)
elif device_category == CATEGORY_CURTAIN:
device = VeraCurtain(item, self)
elif device_category == CATEGORY_ARMABLE:
device = VeraBinarySensor(item, self)
elif (device_category == CATEGORY_SENSOR or
device_category == CATEGORY_HUMIDITY_SENSOR or
device_category == CATEGORY_TEMPERATURE_SENSOR or
device_category == CATEGORY_LIGHT_SENSOR or
device_category == CATEGORY_POWER_METER or
device_category == CATEGORY_UV_SENSOR):
device = VeraSensor(item, self)
elif (device_category == CATEGORY_SCENE_CONTROLLER or
device_category == CATEGORY_REMOTE):
device = VeraSceneController(item, self)
elif device_category == CATEGORY_GARAGE_DOOR:
device = VeraGarageDoor(item, self)
else:
device = VeraDevice(item, self)
self.devices.append(device)
if (device.is_armable and not (
device_category == CATEGORY_SWITCH or
device_category == CATEGORY_VERA_SIREN or
device_category == CATEGORY_CURTAIN or
device_category == CATEGORY_GARAGE_DOOR)):
self.devices.append(VeraArmableDevice(item, self))
else:
self.devices.append(VeraDevice(item, self))
if not category_filter:
return self.devices
devices = []
for device in self.devices:
if (device.category_name is not None and
device.category_name != '' and
device.category_name in category_filter):
devices.append(device)
return devices |
<SYSTEM_TASK:>
Refresh data from Vera device.
<END_TASK>
<USER_TASK:>
Description:
def refresh_data(self):
"""Refresh data from Vera device.""" |
j = self.data_request({'id': 'sdata'}).json()
self.temperature_units = j.get('temperature', 'C')
self.model = j.get('model')
self.version = j.get('version')
self.serial_number = j.get('serial_number')
categories = {}
cats = j.get('categories')
for cat in cats:
categories[cat.get('id')] = cat.get('name')
device_id_map = {}
devs = j.get('devices')
for dev in devs:
dev['categoryName'] = categories.get(dev.get('category'))
device_id_map[dev.get('id')] = dev
return device_id_map |
<SYSTEM_TASK:>
Get full Vera device service info.
<END_TASK>
<USER_TASK:>
Description:
def map_services(self):
"""Get full Vera device service info.""" |
# the Vera rest API is a bit rough so we need to make 2 calls
# to get all the info e need
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
service_map = {}
items = j.get('devices')
for item in items:
service_map[item.get('id')] = item.get('states')
self.device_services_map = service_map |
<SYSTEM_TASK:>
Get data since last timestamp.
<END_TASK>
<USER_TASK:>
Description:
def get_changed_devices(self, timestamp):
"""Get data since last timestamp.
This is done via a blocking call, pass NONE for initial state.
""" |
if timestamp is None:
payload = {}
else:
payload = {
'timeout': SUBSCRIPTION_WAIT,
'minimumdelay': SUBSCRIPTION_MIN_WAIT
}
payload.update(timestamp)
# double the timeout here so requests doesn't timeout before vera
payload.update({
'id': 'lu_sdata',
})
logger.debug("get_changed_devices() requesting payload %s", str(payload))
r = self.data_request(payload, TIMEOUT*2)
r.raise_for_status()
# If the Vera disconnects before writing a full response (as lu_sdata
# will do when interrupted by a Luup reload), the requests module will
# happily return 200 with an empty string. So, test for empty response,
# so we don't rely on the JSON parser to throw an exception.
if r.text == "":
raise PyveraError("Empty response from Vera")
# Catch a wide swath of what the JSON parser might throw, within
# reason. Unfortunately, some parsers don't specifically return
# json.decode.JSONDecodeError, but so far most seem to derive what
# they do throw from ValueError, so that's helpful.
try:
result = r.json()
except ValueError as ex:
raise PyveraError("JSON decode error: " + str(ex))
if not ( type(result) is dict
and 'loadtime' in result and 'dataversion' in result ):
raise PyveraError("Unexpected/garbled response from Vera")
# At this point, all good. Update timestamp and return change data.
device_data = result.get('devices')
timestamp = {
'loadtime': result.get('loadtime'),
'dataversion': result.get('dataversion')
}
return [device_data, timestamp] |
<SYSTEM_TASK:>
Perfom a vera_request for this device.
<END_TASK>
<USER_TASK:>
Description:
def vera_request(self, **kwargs):
"""Perfom a vera_request for this device.""" |
request_payload = {
'output_format': 'json',
'DeviceNum': self.device_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) |
<SYSTEM_TASK:>
Set a variable on the vera device.
<END_TASK>
<USER_TASK:>
Description:
def set_service_value(self, service_id, set_name, parameter_name, value):
"""Set a variable on the vera device.
This will call the Vera api to change device state.
""" |
payload = {
'id': 'lu_action',
'action': 'Set' + set_name,
'serviceId': service_id,
parameter_name: value
}
result = self.vera_request(**payload)
logger.debug("set_service_value: "
"result of vera_request with payload %s: %s",
payload, result.text) |
<SYSTEM_TASK:>
Set a variable in the local state dictionary.
<END_TASK>
<USER_TASK:>
Description:
def set_cache_value(self, name, value):
"""Set a variable in the local state dictionary.
This does not change the physical device. Useful if you want the
device state to refect a new value which has not yet updated drom
Vera.
""" |
dev_info = self.json_state.get('deviceInfo')
if dev_info.get(name.lower()) is None:
logger.error("Could not set %s for %s (key does not exist).",
name, self.name)
logger.error("- dictionary %s", dev_info)
return
dev_info[name.lower()] = str(value) |
<SYSTEM_TASK:>
Set a variable in the local complex state dictionary.
<END_TASK>
<USER_TASK:>
Description:
def set_cache_complex_value(self, name, value):
"""Set a variable in the local complex state dictionary.
This does not change the physical device. Useful if you want the
device state to refect a new value which has not yet updated from
Vera.
""" |
for item in self.json_state.get('states'):
if item.get('variable') == name:
item['value'] = str(value) |
<SYSTEM_TASK:>
Get a value from the service dictionaries.
<END_TASK>
<USER_TASK:>
Description:
def get_complex_value(self, name):
"""Get a value from the service dictionaries.
It's best to use get_value if it has the data you require since
the vera subscription only updates data in dev_info.
""" |
for item in self.json_state.get('states'):
if item.get('variable') == name:
return item.get('value')
return None |
<SYSTEM_TASK:>
Get a case-sensitive keys value from the dev_info area.
<END_TASK>
<USER_TASK:>
Description:
def get_strict_value(self, name):
"""Get a case-sensitive keys value from the dev_info area.
""" |
dev_info = self.json_state.get('deviceInfo')
return dev_info.get(name, None) |
<SYSTEM_TASK:>
Refresh a value from the service dictionaries.
<END_TASK>
<USER_TASK:>
Description:
def refresh_complex_value(self, name):
"""Refresh a value from the service dictionaries.
It's best to use get_value / refresh if it has the data you need.
""" |
for item in self.json_state.get('states'):
if item.get('variable') == name:
service_id = item.get('service')
result = self.vera_request(**{
'id': 'variableget',
'output_format': 'json',
'DeviceNum': self.device_id,
'serviceId': service_id,
'Variable': name
})
item['value'] = result.text
return item.get('value')
return None |
<SYSTEM_TASK:>
Refresh the dev_info data used by get_value.
<END_TASK>
<USER_TASK:>
Description:
def refresh(self):
"""Refresh the dev_info data used by get_value.
Only needed if you're not using subscriptions.
""" |
j = self.vera_request(id='sdata', output_format='json').json()
devices = j.get('devices')
for device_data in devices:
if device_data.get('id') == self.device_id:
self.update(device_data) |
<SYSTEM_TASK:>
Update the dev_info data from a dictionary.
<END_TASK>
<USER_TASK:>
Description:
def update(self, params):
"""Update the dev_info data from a dictionary.
Only updates if it already exists in the device.
""" |
dev_info = self.json_state.get('deviceInfo')
dev_info.update({k: params[k] for k in params if dev_info.get(k)}) |
<SYSTEM_TASK:>
Get level from vera.
<END_TASK>
<USER_TASK:>
Description:
def level(self):
"""Get level from vera.""" |
# Used for dimmers, curtains
# Have seen formats of 10, 0.0 and "0%"!
level = self.get_value('level')
try:
return int(float(level))
except (TypeError, ValueError):
pass
try:
return int(level.strip('%'))
except (TypeError, AttributeError, ValueError):
pass
return 0 |
<SYSTEM_TASK:>
Set the switch state, also update local state.
<END_TASK>
<USER_TASK:>
Description:
def set_switch_state(self, state):
"""Set the switch state, also update local state.""" |
self.set_service_value(
self.switch_service,
'Target',
'newTargetValue',
state)
self.set_cache_value('Status', state) |
<SYSTEM_TASK:>
Get dimmer state.
<END_TASK>
<USER_TASK:>
Description:
def is_switched_on(self, refresh=False):
"""Get dimmer state.
Refresh data from Vera if refresh is True,
otherwise use local cache. Refresh is only needed if you're
not using subscriptions.
""" |
if refresh:
self.refresh()
return self.get_brightness(refresh) > 0 |
<SYSTEM_TASK:>
Get dimmer brightness.
<END_TASK>
<USER_TASK:>
Description:
def get_brightness(self, refresh=False):
"""Get dimmer brightness.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
Converts the Vera level property for dimmable lights from a percentage
to the 0 - 255 scale used by HA.
""" |
if refresh:
self.refresh()
brightness = 0
percent = self.level
if percent > 0:
brightness = round(percent * 2.55)
return int(brightness) |
<SYSTEM_TASK:>
Set dimmer brightness.
<END_TASK>
<USER_TASK:>
Description:
def set_brightness(self, brightness):
"""Set dimmer brightness.
Converts the Vera level property for dimmable lights from a percentage
to the 0 - 255 scale used by HA.
""" |
percent = 0
if brightness > 0:
percent = round(brightness / 2.55)
self.set_service_value(
self.dimmer_service,
'LoadLevelTarget',
'newLoadlevelTarget',
percent)
self.set_cache_value('level', percent) |
<SYSTEM_TASK:>
Get color index.
<END_TASK>
<USER_TASK:>
Description:
def get_color_index(self, colors, refresh=False):
"""Get color index.
Refresh data from Vera if refresh is True, otherwise use local cache.
""" |
if refresh:
self.refresh_complex_value('SupportedColors')
sup = self.get_complex_value('SupportedColors')
if sup is None:
return None
sup = sup.split(',')
if not set(colors).issubset(sup):
return None
return [sup.index(c) for c in colors] |
<SYSTEM_TASK:>
Get color.
<END_TASK>
<USER_TASK:>
Description:
def get_color(self, refresh=False):
"""Get color.
Refresh data from Vera if refresh is True, otherwise use local cache.
""" |
if refresh:
self.refresh_complex_value('CurrentColor')
ci = self.get_color_index(['R', 'G', 'B'], refresh)
cur = self.get_complex_value('CurrentColor')
if ci is None or cur is None:
return None
try:
val = [cur.split(',')[c] for c in ci]
return [int(v.split('=')[1]) for v in val]
except IndexError:
return None |
<SYSTEM_TASK:>
Set the armed state, also update local state.
<END_TASK>
<USER_TASK:>
Description:
def set_armed_state(self, state):
"""Set the armed state, also update local state.""" |
self.set_service_value(
self.security_sensor_service,
'Armed',
'newArmedValue',
state)
self.set_cache_value('Armed', state) |
<SYSTEM_TASK:>
Get armed state.
<END_TASK>
<USER_TASK:>
Description:
def is_switched_on(self, refresh=False):
"""Get armed state.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
""" |
if refresh:
self.refresh()
val = self.get_value('Armed')
return val == '1' |
<SYSTEM_TASK:>
Get curtains state.
<END_TASK>
<USER_TASK:>
Description:
def is_open(self, refresh=False):
"""Get curtains state.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
""" |
if refresh:
self.refresh()
return self.get_level(refresh) > 0 |
<SYSTEM_TASK:>
Set open level of the curtains.
<END_TASK>
<USER_TASK:>
Description:
def set_level(self, level):
"""Set open level of the curtains.
Scale is 0-100
""" |
self.set_service_value(
self.dimmer_service,
'LoadLevelTarget',
'newLoadlevelTarget',
level)
self.set_cache_value('level', level) |
<SYSTEM_TASK:>
Get the list of PIN codes
<END_TASK>
<USER_TASK:>
Description:
def get_pin_codes(self, refresh=False):
"""Get the list of PIN codes
Codes can also be found with self.get_complex_value('PinCodes')
""" |
if refresh:
self.refresh()
val = self.get_value("pincodes")
# val syntax string: <VERSION=3>next_available_user_code_id\tuser_code_id,active,date_added,date_used,PIN_code,name;\t...
# See (outdated) http://wiki.micasaverde.com/index.php/Luup_UPnP_Variables_and_Actions#DoorLock1
# Remove the trailing tab
# ignore the version and next available at the start
# and split out each set of code attributes
raw_code_list = []
try:
raw_code_list = val.rstrip().split('\t')[1:]
except Exception as ex:
logger.error('Got unsupported string {}: {}'.format(val, ex))
# Loop to create a list of codes
codes = []
for code in raw_code_list:
try:
# Strip off trailing semicolon
# Create a list from csv
code_addrs = code.split(';')[0].split(',')
# Get the code ID (slot) and see if it should have values
slot, active = code_addrs[:2]
if active != '0':
# Since it has additional attributes, get the remaining ones
_, _, pin, name = code_addrs[2:]
# And add them as a tuple to the list
codes.append((slot, name, pin))
except Exception as ex:
logger.error('Problem parsing pin code string {}: {}'.format(code, ex))
return codes |
<SYSTEM_TASK:>
Get last scene id.
<END_TASK>
<USER_TASK:>
Description:
def get_last_scene_id(self, refresh=False):
"""Get last scene id.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
""" |
if refresh:
self.refresh_complex_value('LastSceneID')
self.refresh_complex_value('sl_CentralScene')
val = self.get_complex_value('LastSceneID') or self.get_complex_value('sl_CentralScene')
return val |
<SYSTEM_TASK:>
Get last scene time.
<END_TASK>
<USER_TASK:>
Description:
def get_last_scene_time(self, refresh=False):
"""Get last scene time.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
""" |
if refresh:
self.refresh_complex_value('LastSceneTime')
val = self.get_complex_value('LastSceneTime')
return val |
<SYSTEM_TASK:>
Perfom a vera_request for this scene.
<END_TASK>
<USER_TASK:>
Description:
def vera_request(self, **kwargs):
"""Perfom a vera_request for this scene.""" |
request_payload = {
'output_format': 'json',
'SceneNum': self.scene_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) |
<SYSTEM_TASK:>
Activate a Vera scene.
<END_TASK>
<USER_TASK:>
Description:
def activate(self):
"""Activate a Vera scene.
This will call the Vera api to activate a scene.
""" |
payload = {
'id': 'lu_action',
'action': 'RunScene',
'serviceId': self.scene_service
}
result = self.vera_request(**payload)
logger.debug("activate: "
"result of vera_request with payload %s: %s",
payload, result.text)
self._active = True |
<SYSTEM_TASK:>
Refresh the data used by get_value.
<END_TASK>
<USER_TASK:>
Description:
def refresh(self):
"""Refresh the data used by get_value.
Only needed if you're not using subscriptions.
""" |
j = self.vera_request(id='sdata', output_format='json').json()
scenes = j.get('scenes')
for scene_data in scenes:
if scene_data.get('id') == self.scene_id:
self.update(scene_data) |
<SYSTEM_TASK:>
Remove a registered a callback.
<END_TASK>
<USER_TASK:>
Description:
def unregister(self, device, callback):
"""Remove a registered a callback.
device: device that has the subscription
callback: callback used in original registration
""" |
if not device:
logger.error("Received an invalid device: %r", device)
return
logger.debug("Removing subscription for {}".format(device.name))
self._callbacks[device].remove(callback)
self._devices[device.vera_device_id].remove(device) |
<SYSTEM_TASK:>
Start a thread to handle Vera blocked polling.
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""Start a thread to handle Vera blocked polling.""" |
self._poll_thread = threading.Thread(target=self._run_poll_server,
name='Vera Poll Thread')
self._poll_thread.deamon = True
self._poll_thread.start() |
<SYSTEM_TASK:>
Choose between small, medium, large, ... depending on the
<END_TASK>
<USER_TASK:>
Description:
def _pick_level(cls, btc_amount):
"""
Choose between small, medium, large, ... depending on the
amount specified.
""" |
for size, level in cls.TICKER_LEVEL:
if btc_amount < size:
return level
return cls.TICKER_LEVEL[-1][1] |
<SYSTEM_TASK:>
Render a single line for TSV file with data flow described
<END_TASK>
<USER_TASK:>
Description:
def format_tsv_line(source, edge, target, value=None, metadata=None):
"""
Render a single line for TSV file with data flow described
:type source str
:type edge str
:type target str
:type value float
:type metadata str
:rtype: str
""" |
return '{source}\t{edge}\t{target}\t{value}\t{metadata}'.format(
source=source,
edge=edge,
target=target,
value='{:.4f}'.format(value) if value is not None else '',
metadata=metadata or ''
).rstrip(' \t') |
<SYSTEM_TASK:>
Render a .dot file with graph definition from a given set of data
<END_TASK>
<USER_TASK:>
Description:
def format_graphviz_lines(lines):
"""
Render a .dot file with graph definition from a given set of data
:type lines list[dict]
:rtype: str
""" |
# first, prepare the unique list of all nodes (sources and targets)
lines_nodes = set()
for line in lines:
lines_nodes.add(line['source'])
lines_nodes.add(line['target'])
# generate a list of all nodes and their names for graphviz graph
nodes = OrderedDict()
for i, node in enumerate(sorted(lines_nodes)):
nodes[node] = 'n{}'.format(i+1)
# print(lines_nodes, nodes)
graph = list()
# some basic style definition
# https://graphviz.gitlab.io/_pages/doc/info/lang.html
graph.append('digraph G {')
# https://graphviz.gitlab.io/_pages/doc/info/shapes.html#record
graph.append('\tgraph [ center=true, margin=0.75, nodesep=0.5, ranksep=0.75, rankdir=LR ];')
graph.append('\tnode [ shape=box, style="rounded,filled" width=0, height=0, '
'fontname=Helvetica, fontsize=11 ];')
graph.append('\tedge [ fontname=Helvetica, fontsize=9 ];')
# emit nodes definition
graph.append('\n\t// nodes')
# https://www.graphviz.org/doc/info/colors.html#brewer
group_colors = dict()
for label, name in nodes.items():
if ':' in label:
(group, label) = str(label).split(':', 1)
# register a new group for coloring
if group not in group_colors:
group_colors[group] = len(group_colors.keys()) + 1
else:
group = None
label = escape_graphviz_entry(label)
graph.append('\t{name} [label="{label}"{group}];'.format(
name=name,
label="{}\\n{}".format(group, label) if group is not None else label,
group=' group="{}" colorscheme=pastel28 color={}'.format(
group, group_colors[group]) if group is not None else ''
))
# now, connect the nodes
graph.append('\n\t// edges')
for line in lines:
label = line.get('metadata', '')
graph.append('\t{source} -> {target} [{label}];'.format(
source=nodes[line['source']],
target=nodes[line['target']],
label='label="{}"'.format(escape_graphviz_entry(label)) if label != '' else ''
))
graph.append('}')
return '\n'.join(graph) |
<SYSTEM_TASK:>
Open a websocket connection to remote browser, determined by
<END_TASK>
<USER_TASK:>
Description:
def connect(self, tab_key):
"""
Open a websocket connection to remote browser, determined by
self.host and self.port. Each tab has it's own websocket
endpoint.
""" |
assert self.tablist is not None
tab_idx = self._get_tab_idx_for_key(tab_key)
if not self.tablist:
self.tablist = self.fetch_tablist()
for fails in range(9999):
try:
# If we're one past the end of the tablist, we need to create a new tab
if tab_idx is None:
self.log.debug("Creating new tab (%s active)", len(self.tablist))
self.__create_new_tab(tab_key)
self.__connect_to_tab(tab_key)
break
except cr_exceptions.ChromeConnectFailure as e:
if fails > 6:
self.log.error("Failed to fetch tab websocket URL after %s retries. Aborting!", fails)
raise e
self.log.info("Tab may not have started yet (%s tabs active). Recreating.", len(self.tablist))
# self.log.info("Tag: %s", self.tablist[tab_idx])
# For reasons I don't understand, sometimes a new tab doesn't get a websocket
# debugger URL. Anyways, we close and re-open the tab if that happens.
# TODO: Handle the case when this happens on the first tab. I think closing the first
# tab will kill chromium.
self.__close_tab(tab_key) |
<SYSTEM_TASK:>
Close websocket connection to remote browser.
<END_TASK>
<USER_TASK:>
Description:
def close_websockets(self):
""" Close websocket connection to remote browser.""" |
self.log.info("Websocket Teardown called")
for key in list(self.soclist.keys()):
if self.soclist[key]:
self.soclist[key].close()
self.soclist.pop(key) |
<SYSTEM_TASK:>
Synchronously execute command `command` with params `params` in the
<END_TASK>
<USER_TASK:>
Description:
def synchronous_command(self, command, tab_key, **params):
"""
Synchronously execute command `command` with params `params` in the
remote chrome instance, returning the response from the chrome instance.
""" |
self.log.debug("Synchronous_command to tab %s (%s):", tab_key, self._get_cr_tab_meta_for_key(tab_key))
self.log.debug(" command: '%s'", command)
self.log.debug(" params: '%s'", params)
self.log.debug(" tab_key: '%s'", tab_key)
send_id = self.send(command=command, tab_key=tab_key, params=params)
resp = self.recv(message_id=send_id, tab_key=tab_key)
self.log.debug(" Response: '%s'", str(resp).encode("ascii", 'ignore').decode("ascii"))
# self.log.debug(" resolved tab idx %s:", self.tab_id_map[tab_key])
return resp |
<SYSTEM_TASK:>
Return a function to be run in a child process which will trigger SIGNAME
<END_TASK>
<USER_TASK:>
Description:
def on_parent_exit(signame):
"""
Return a function to be run in a child process which will trigger SIGNAME
to be sent when the parent process dies
""" |
signum = getattr(signal, signame)
def set_parent_exit_signal():
# http://linux.die.net/man/2/prctl
result = cdll['libc.so.6'].prctl(PR_SET_PDEATHSIG, signum)
if result != 0:
raise PrCtlError('prctl failed with error code %s' % result)
return set_parent_exit_signal |
<SYSTEM_TASK:>
This is the version from Django 1.7.
<END_TASK>
<USER_TASK:>
Description:
def run_suite(self, suite, **kwargs):
"""This is the version from Django 1.7.""" |
return self.test_runner(
verbosity=self.verbosity,
failfast=self.failfast,
no_colour=self.no_colour,
).run(suite) |
<SYSTEM_TASK:>
Generates shared secret from the other party's public key.
<END_TASK>
<USER_TASK:>
Description:
def generate_shared_secret(self, other_public_key, echo_return_key=False):
"""
Generates shared secret from the other party's public key.
:param other_public_key: Other party's public key
:type other_public_key: int
:param echo_return_key: Echo return shared key
:type bool
:return: void
:rtype: void
""" |
if self.verify_public_key(other_public_key) is False:
raise MalformedPublicKey
self.shared_secret = pow(other_public_key,
self.__private_key,
self.prime)
shared_secret_as_bytes = self.shared_secret.to_bytes(self.shared_secret.bit_length() // 8 + 1, byteorder='big')
_h = sha256()
_h.update(bytes(shared_secret_as_bytes))
self.shared_key = _h.hexdigest()
if echo_return_key is True:
return self.shared_key |
<SYSTEM_TASK:>
Decorator for functions that require the private key to be defined.
<END_TASK>
<USER_TASK:>
Description:
def requires_private_key(func):
"""
Decorator for functions that require the private key to be defined.
""" |
def func_wrapper(self, *args, **kwargs):
if hasattr(self, "_DiffieHellman__private_key"):
func(self, *args, **kwargs)
else:
self.generate_private_key()
func(self, *args, **kwargs)
return func_wrapper |
<SYSTEM_TASK:>
Decorator for functions that require the public key to be defined. By definition, this includes the private key, as such, it's enough to use this to effect definition of both public and private key.
<END_TASK>
<USER_TASK:>
Description:
def requires_public_key(func):
"""
Decorator for functions that require the public key to be defined. By definition, this includes the private key, as such, it's enough to use this to effect definition of both public and private key.
""" |
def func_wrapper(self, *args, **kwargs):
if hasattr(self, "public_key"):
func(self, *args, **kwargs)
else:
self.generate_public_key()
func(self, *args, **kwargs)
return func_wrapper |
<SYSTEM_TASK:>
Print if and only if the debug flag is set true in the config.yaml file.
<END_TASK>
<USER_TASK:>
Description:
def print_debug(*args, **kwargs):
"""
Print if and only if the debug flag is set true in the config.yaml file.
Args:
args : var args of print arguments.
""" |
if WTF_CONFIG_READER.get("debug", False) == True:
print(*args, **kwargs) |
<SYSTEM_TASK:>
Print the current elapsed time.
<END_TASK>
<USER_TASK:>
Description:
def print_time(self, message="Time is now: ", print_frame_info=True):
"""
Print the current elapsed time.
Kwargs:
message (str) : Message to prefix the time stamp.
print_frame_info (bool) : Add frame info to the print message.
""" |
if print_frame_info:
frame_info = inspect.getouterframes(inspect.currentframe())[1]
print(message, (datetime.now() - self.start_time), frame_info)
else:
print(message, (datetime.now() - self.start_time)) |
<SYSTEM_TASK:>
Utility method for switching between windows. It will search through currently open
<END_TASK>
<USER_TASK:>
Description:
def switch_to_window(page_class, webdriver):
"""
Utility method for switching between windows. It will search through currently open
windows, then switch to the window matching the provided PageObject class.
Args:
page_class (PageObject): Page class to search for/instantiate.
webdriver (WebDriver): Selenium webdriver.
Usage::
WebUtils.switch_to_window(DetailsPopUpPage, driver) # switches to the pop up window.
""" |
window_list = list(webdriver.window_handles)
original_window = webdriver.current_window_handle
for window_handle in window_list:
webdriver.switch_to_window(window_handle)
try:
return PageFactory.create_page(page_class, webdriver)
except:
pass
webdriver.switch_to_window(original_window)
raise WindowNotFoundError(
u("Window {0} not found.").format(page_class.__class__.__name__)) |
<SYSTEM_TASK:>
Start standing by. A periodic command like 'current_url' will be sent to the
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""
Start standing by. A periodic command like 'current_url' will be sent to the
webdriver instance to prevent it from timing out.
""" |
self._end_time = datetime.now() + timedelta(seconds=self._max_time)
self._thread = Thread(target=lambda: self.__stand_by_loop())
self._keep_running = True
self._thread.start()
return self |
<SYSTEM_TASK:>
Gets a temp path.
<END_TASK>
<USER_TASK:>
Description:
def temp_path(file_name=None):
"""
Gets a temp path.
Kwargs:
file_name (str) : if file name is specified, it gets appended to the temp dir.
Usage::
temp_file_path = temp_path("myfile")
copyfile("myfile", temp_file_path) # copies 'myfile' to '/tmp/myfile'
""" |
if file_name is None:
file_name = generate_timestamped_string("wtf_temp_file")
return os.path.join(tempfile.gettempdir(), file_name) |
<SYSTEM_TASK:>
Downloads a URL contents to a tempfile. This is useful for testing downloads.
<END_TASK>
<USER_TASK:>
Description:
def download_to_tempfile(url, file_name=None, extension=None):
"""
Downloads a URL contents to a tempfile. This is useful for testing downloads.
It will download the contents of a URL to a tempfile, which you then can
open and use to validate the downloaded contents.
Args:
url (str) : URL of the contents to download.
Kwargs:
file_name (str): Name of file.
extension (str): Extension to use.
Return:
str - Returns path to the temp file.
""" |
if not file_name:
file_name = generate_timestamped_string("wtf_temp_file")
if extension:
file_path = temp_path(file_name + extension)
else:
ext = ""
try:
ext = re.search(u"\\.\\w+$", file_name).group(0)
except:
pass
file_path = temp_path(file_name + ext)
webFile = urllib.urlopen(url)
localFile = open(file_path, 'w')
localFile.write(webFile.read())
webFile.close()
localFile.close()
return file_path |
<SYSTEM_TASK:>
Class method short cut to call PageFactory on itself. Use it to instantiate
<END_TASK>
<USER_TASK:>
Description:
def create_page(cls, webdriver=None, **kwargs):
"""Class method short cut to call PageFactory on itself. Use it to instantiate
this PageObject using a webdriver.
Args:
webdriver (Webdriver): Instance of Selenium Webdriver.
Returns:
PageObject
Raises:
InvalidPageError
""" |
if not webdriver:
webdriver = WTF_WEBDRIVER_MANAGER.get_driver()
return PageFactory.create_page(cls, webdriver=webdriver, **kwargs) |
<SYSTEM_TASK:>
Instantiate a page object from a given Interface or Abstract class.
<END_TASK>
<USER_TASK:>
Description:
def create_page(page_object_class_or_interface,
webdriver=None, **kwargs):
"""
Instantiate a page object from a given Interface or Abstract class.
Args:
page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or
Interface to attempt to consturct.
Kwargs:
webdriver (WebDriver): Selenium Webdriver to use to instantiate the page. If none
is provided, then it was use the default from
WTF_WEBDRIVER_MANAGER
Returns:
PageObject
Raises:
NoMatchingPageError
Instantiating a Page from PageObject from class usage::
my_page_instance = PageFactory.create_page(MyPageClass)
Instantiating a Page from an Interface or base class::
import pages.mysite.* # Make sure you import classes first, or else PageFactory will not know about it.
my_page_instance = PageFactory.create_page(MyPageInterfaceClass)
Instantiating a Page from a list of classes.::
my_page_instance = PageFactory.create_page([PossiblePage1, PossiblePage2])
Note: It'll only be able to detect pages that are imported. To it's best to
do an import of all pages implementing a base class or the interface inside the
__init__.py of the package directory.
""" |
if not webdriver:
webdriver = WTF_WEBDRIVER_MANAGER.get_driver()
# will be used later when tracking best matched page.
current_matched_page = None
# used to track if there is a valid page object within the set of PageObjects searched.
was_validate_called = False
# Walk through all classes if a list was passed.
if type(page_object_class_or_interface) == list:
subclasses = []
for page_class in page_object_class_or_interface:
# attempt to instantiate class.
page = PageFactory.__instantiate_page_object(page_class,
webdriver,
**kwargs)
if isinstance(page, PageObject):
was_validate_called = True
if (current_matched_page == None or page > current_matched_page):
current_matched_page = page
elif page is True:
was_validate_called = True
# check for subclasses
subclasses += PageFactory.__itersubclasses(page_class)
else:
# A single class was passed in, try to instantiate the class.
page_class = page_object_class_or_interface
page = PageFactory.__instantiate_page_object(page_class,
webdriver,
**kwargs)
# Check if we got a valid PageObject back.
if isinstance(page, PageObject):
was_validate_called = True
current_matched_page = page
elif page is True:
was_validate_called = True
# check for subclasses
subclasses = PageFactory.__itersubclasses(
page_object_class_or_interface)
# Iterate over subclasses of the passed in classes to see if we have a
# better match.
for pageClass in subclasses:
try:
page = PageFactory.__instantiate_page_object(pageClass,
webdriver,
**kwargs)
# If we get a valid PageObject match, check to see if the ranking is higher
# than our current PageObject.
if isinstance(page, PageObject):
was_validate_called = True
if current_matched_page == None or page > current_matched_page:
current_matched_page = page
elif page is True:
was_validate_called = True
except InvalidPageError as e:
_wtflog.debug("InvalidPageError: %s", e)
pass # This happens when the page fails check.
except TypeError as e:
_wtflog.debug("TypeError: %s", e)
# this happens when it tries to instantiate the original
# abstract class.
pass
except Exception as e:
_wtflog.debug("Exception during page instantiation: %s", e)
# Unexpected exception.
raise e
# If no matching classes.
if not isinstance(current_matched_page, PageObject):
# Check that there is at least 1 valid page object that was passed in.
if was_validate_called is False:
raise TypeError("Neither the PageObjects nor it's subclasses have implemented " +
"'PageObject._validate(self, webdriver)'.")
try:
current_url = webdriver.current_url
raise NoMatchingPageError(u("There's, no matching classes to this page. URL:{0}")
.format(current_url))
except:
raise NoMatchingPageError(u("There's, no matching classes to this page. "))
else:
return current_matched_page |
<SYSTEM_TASK:>
Attempts to instantiate a page object.
<END_TASK>
<USER_TASK:>
Description:
def __instantiate_page_object(page_obj_class, webdriver, **kwargs):
"""
Attempts to instantiate a page object.
Args:
page_obj_class (PageObject) - PageObject to instantiate.
webdriver (WebDriver) - Selenium webdriver to associate with the PageObject
Returns:
PageObject - If page object instantiation succeeded.
True - If page object instantiation failed, but validation was called.
None - If validation did not occur.
""" |
try:
page = page_obj_class(webdriver, **kwargs)
return page
except InvalidPageError:
# This happens when the page fails check.
# Means validate was implemented, but the check didn't pass.
return True
except TypeError:
# this happens when it tries to instantiate the original abstract
# class, or a PageObject where _validate() was not implemented.
return False
except Exception as e:
# Unexpected exception.
raise e |
<SYSTEM_TASK:>
Returns true if all CSS selectors passed in is found. This can be used
<END_TASK>
<USER_TASK:>
Description:
def check_css_selectors(webdriver, *selectors):
"""Returns true if all CSS selectors passed in is found. This can be used
to quickly validate a page.
Args:
webdriver (Webdriver) : Selenium Webdriver instance
selectors (str) : N number of CSS selectors strings to match against the page.
Returns:
True, False - if the page matches all selectors.
Usage Example::
# Checks for a Form with id='loginForm' and a button with class 'login'
if not PageObjectUtils.check_css_selectors("form#loginForm", "button.login"):
raise InvalidPageError("This is not the login page.")
You can use this within a PageObject's `_validate_page(webdriver)` method for
validating pages.
""" |
for selector in selectors:
try:
webdriver.find_element_by_css_selector(selector)
except:
return False # A selector failed.
return True |
<SYSTEM_TASK:>
Waits until the page is loaded.
<END_TASK>
<USER_TASK:>
Description:
def wait_until_page_loaded(page_obj_class,
webdriver=None,
timeout=WTF_TIMEOUT_MANAGER.NORMAL,
sleep=0.5,
bad_page_classes=[],
message=None,
**kwargs):
"""
Waits until the page is loaded.
Args:
page_obj_class (Class) : PageObject class
Kwargs:
webdriver (Webdriver) : Selenium Webdriver. Default uses WTF_WEBDRIVER_MANAGER's instance.
timeout (number) : Number of seconds to wait to allow the page to load.
sleep (number) : Number of seconds to wait between polling.
bad_page_classes (list) : List of PageObject classes to fail if matched. For example, ServerError page.
message (string) : Use your own message with PageLoadTimeoutError raised.
Returns:
PageObject
Raises:
PageUtilOperationTimeoutError : Timeout occurred before the desired PageObject was matched.
BadPageEncounteredError : One or more of the PageObject in the specified 'bad_page_classes' list
was matched.
Usage Example::
webdriver.get("http://www.mysite.com/login")
# Wait up to 60 seconds for the page to load.
login_page = wait_until_page_loaded(LoginPage, timeout=60, [ServerErrorPage])
This will wait for the login_page to load, then return a LoginPage() PageObject.
""" |
if not webdriver:
webdriver = WTF_WEBDRIVER_MANAGER.get_driver()
# convert this param to list if not already.
if type(bad_page_classes) != list:
bad_page_classes = [bad_page_classes]
end_time = datetime.now() + timedelta(seconds=timeout)
last_exception = None
while datetime.now() < end_time:
# Check to see if we're at our target page.
try:
page = PageFactory.create_page(
page_obj_class, webdriver=webdriver, **kwargs)
return page
except Exception as e:
_wtflog.debug("Encountered exception: %s ", e)
last_exception = e
# Check to see if we're at one of those labled 'Bad' pages.
for bad_page_class in bad_page_classes:
try:
PageFactory.create_page(
bad_page_class, webdriver=webdriver, **kwargs)
# if the if/else statement succeeds, than we have an error.
raise BadPageEncounteredError(
u("Encountered a bad page. ") + bad_page_class.__name__)
except BadPageEncounteredError as e:
raise e
except:
pass # We didn't hit a bad page class yet.
# sleep till the next iteration.
time.sleep(sleep)
print "Unable to construct page, last exception", last_exception
# Attempt to get current URL to assist in debugging
try:
current_url = webdriver.current_url
except:
# unable to get current URL, could be a webdriver for a non-webpage like mobile app.
current_url = None
if message:
err_msg = u(message) + u("{page}:{url}")\
.format(page=PageUtils.__get_name_for_class__(page_obj_class),
url=current_url)
else:
err_msg = u("Timed out while waiting for {page} to load. Url:{url}")\
.format(page=PageUtils.__get_name_for_class__(page_obj_class),
url=current_url)
raise PageLoadTimeoutError(err_msg) |
<SYSTEM_TASK:>
Get the full system path of a given asset if it exists. Otherwise it throws
<END_TASK>
<USER_TASK:>
Description:
def get_asset_path(self, filename):
"""
Get the full system path of a given asset if it exists. Otherwise it throws
an error.
Args:
filename (str) - File name of a file in /assets folder to fetch the path for.
Returns:
str - path to the target file.
Raises:
AssetNotFoundError - if asset does not exist in the asset folder.
Usage::
path = WTF_ASSET_MANAGER.get_asset_path("my_asset.png")
# path = /your/workspace/location/WTFProjectName/assets/my_asset.png
""" |
if os.path.exists(os.path.join(self._asset_path, filename)):
return os.path.join(self._asset_path, filename)
else:
raise AssetNotFoundError(
u("Cannot find asset: {0}").format(filename)) |
<SYSTEM_TASK:>
Captures a screenshot.
<END_TASK>
<USER_TASK:>
Description:
def take_screenshot(webdriver, file_name):
"""
Captures a screenshot.
Args:
webdriver (WebDriver) - Selenium webdriver.
file_name (str) - File name to save screenshot as.
""" |
folder_location = os.path.join(ProjectUtils.get_project_root(),
WebScreenShotUtil.SCREEN_SHOT_LOCATION)
WebScreenShotUtil.__capture_screenshot(
webdriver, folder_location, file_name + ".png") |
<SYSTEM_TASK:>
Captures a screenshot as a reference screenshot.
<END_TASK>
<USER_TASK:>
Description:
def take_reference_screenshot(webdriver, file_name):
"""
Captures a screenshot as a reference screenshot.
Args:
webdriver (WebDriver) - Selenium webdriver.
file_name (str) - File name to save screenshot as.
""" |
folder_location = os.path.join(ProjectUtils.get_project_root(),
WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION)
WebScreenShotUtil.__capture_screenshot(
webdriver, folder_location, file_name + ".png") |
<SYSTEM_TASK:>
Searches for Email by Subject. Returns True or False.
<END_TASK>
<USER_TASK:>
Description:
def check_email_exists_by_subject(self, subject, match_recipient=None):
"""
Searches for Email by Subject. Returns True or False.
Args:
subject (str): Subject to search for.
Kwargs:
match_recipient (str) : Recipient to match exactly. (don't care if not specified)
Returns:
True - email found, False - email not found
""" |
# Select inbox to fetch the latest mail on server.
self._mail.select("inbox")
try:
matches = self.__search_email_by_subject(subject, match_recipient)
if len(matches) <= 0:
return False
else:
return True
except Exception as e:
raise e |
<SYSTEM_TASK:>
Searches for Email by Subject. Returns email's imap message IDs
<END_TASK>
<USER_TASK:>
Description:
def find_emails_by_subject(self, subject, limit=50, match_recipient=None):
"""
Searches for Email by Subject. Returns email's imap message IDs
as a list if matching subjects is found.
Args:
subject (str) - Subject to search for.
Kwargs:
limit (int) - Limit search to X number of matches, default 50
match_recipient (str) - Recipient to exactly (don't care if not specified)
Returns:
list - List of Integers representing imap message UIDs.
""" |
# Select inbox to fetch the latest mail on server.
self._mail.select("inbox")
matching_uids = self.__search_email_by_subject(
subject, match_recipient)
return matching_uids |
<SYSTEM_TASK:>
Gets next entry as a dictionary.
<END_TASK>
<USER_TASK:>
Description:
def next(self):
"""
Gets next entry as a dictionary.
Returns:
object - Object key/value pair representing a row.
{key1: value1, key2: value2, ...}
""" |
try:
entry = {}
row = self._csv_reader.next()
for i in range(0, len(row)):
entry[self._headers[i]] = row[i]
return entry
except Exception as e:
# close our file when we're done reading.
self._file.close()
raise e |
<SYSTEM_TASK:>
Wait for a WebElement to disappear.
<END_TASK>
<USER_TASK:>
Description:
def wait_until_element_not_visible(webdriver, locator_lambda_expression,
timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5):
"""
Wait for a WebElement to disappear.
Args:
webdriver (Webdriver) - Selenium Webdriver
locator (lambda) - Locator lambda expression.
Kwargs:
timeout (number) - timeout period
sleep (number) - sleep period between intervals.
""" |
# Wait for loading progress indicator to go away.
try:
stoptime = datetime.now() + timedelta(seconds=timeout)
while datetime.now() < stoptime:
element = WebDriverWait(webdriver, WTF_TIMEOUT_MANAGER.BRIEF).until(
locator_lambda_expression)
if element.is_displayed():
time.sleep(sleep)
else:
break
except TimeoutException:
pass |
<SYSTEM_TASK:>
Generate time-stamped string. Format as follows...
<END_TASK>
<USER_TASK:>
Description:
def generate_timestamped_string(subject="test", number_of_random_chars=4):
"""
Generate time-stamped string. Format as follows...
`2013-01-31_14:12:23_SubjectString_a3Zg`
Kwargs:
subject (str): String to use as subject.
number_of_random_chars (int) : Number of random characters to append.
This method is helpful for creating unique names with timestamps in them so
when you have to troubleshoot an issue, the name is easier to find.::
self.project_name = generate_timestamped_string("project")
new_project_page.create_project(project_name)
""" |
random_str = generate_random_string(number_of_random_chars)
timestamp = generate_timestamp()
return u"{timestamp}_{subject}_{random_str}".format(timestamp=timestamp,
subject=subject,
random_str=random_str) |
<SYSTEM_TASK:>
Generate a series of random characters.
<END_TASK>
<USER_TASK:>
Description:
def generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters):
"""
Generate a series of random characters.
Kwargs:
number_of_random_chars (int) : Number of characters long
character_set (str): Specify a character set. Default is ASCII
""" |
return u('').join(random.choice(character_set)
for _ in range(number_of_random_chars)) |
<SYSTEM_TASK:>
Returns the value associated with the given value index
<END_TASK>
<USER_TASK:>
Description:
def get_attribute_value(self, name, index):
"""
Returns the value associated with the given value index
of the attribute with the given name.
This is only applicable for nominal and string types.
""" |
if index == MISSING:
return
elif self.attribute_types[name] in NUMERIC_TYPES:
at = self.attribute_types[name]
if at == TYPE_INTEGER:
return int(index)
return Decimal(str(index))
else:
assert self.attribute_types[name] == TYPE_NOMINAL
cls_index, cls_value = index.split(':')
#return self.attribute_data[name][index-1]
if cls_value != MISSING:
assert cls_value in self.attribute_data[name], \
'Predicted value "%s" but only values %s are allowed.' \
% (cls_value, ', '.join(self.attribute_data[name]))
return cls_value |
<SYSTEM_TASK:>
Load an ARFF File from a file.
<END_TASK>
<USER_TASK:>
Description:
def load(cls, filename, schema_only=False):
"""
Load an ARFF File from a file.
""" |
o = open(filename)
s = o.read()
a = cls.parse(s, schema_only=schema_only)
if not schema_only:
a._filename = filename
o.close()
return a |
<SYSTEM_TASK:>
Parse an ARFF File already loaded into a string.
<END_TASK>
<USER_TASK:>
Description:
def parse(cls, s, schema_only=False):
"""
Parse an ARFF File already loaded into a string.
""" |
a = cls()
a.state = 'comment'
a.lineno = 1
for l in s.splitlines():
a.parseline(l)
a.lineno += 1
if schema_only and a.state == 'data':
# Don't parse data if we're only loading the schema.
break
return a |
<SYSTEM_TASK:>
Creates a deepcopy of the instance.
<END_TASK>
<USER_TASK:>
Description:
def copy(self, schema_only=False):
"""
Creates a deepcopy of the instance.
If schema_only is True, the data will be excluded from the copy.
""" |
o = type(self)()
o.relation = self.relation
o.attributes = list(self.attributes)
o.attribute_types = self.attribute_types.copy()
o.attribute_data = self.attribute_data.copy()
if not schema_only:
o.comment = list(self.comment)
o.data = copy.deepcopy(self.data)
return o |
<SYSTEM_TASK:>
Save an arff structure to a file, leaving the file object
<END_TASK>
<USER_TASK:>
Description:
def open_stream(self, class_attr_name=None, fn=None):
"""
Save an arff structure to a file, leaving the file object
open for writing of new data samples.
This prevents you from directly accessing the data via Python,
but when generating a huge file, this prevents all your data
from being stored in memory.
""" |
if fn:
self.fout_fn = fn
else:
fd, self.fout_fn = tempfile.mkstemp()
os.close(fd)
self.fout = open(self.fout_fn, 'w')
if class_attr_name:
self.class_attr_name = class_attr_name
self.write(fout=self.fout, schema_only=True)
self.write(fout=self.fout, data_only=True)
self.fout.flush() |
<SYSTEM_TASK:>
Terminates an open stream and returns the filename
<END_TASK>
<USER_TASK:>
Description:
def close_stream(self):
"""
Terminates an open stream and returns the filename
of the file containing the streamed data.
""" |
if self.fout:
fout = self.fout
fout_fn = self.fout_fn
self.fout.flush()
self.fout.close()
self.fout = None
self.fout_fn = None
return fout_fn |
<SYSTEM_TASK:>
Save an arff structure to a file.
<END_TASK>
<USER_TASK:>
Description:
def save(self, filename=None):
"""
Save an arff structure to a file.
""" |
filename = filename or self._filename
o = open(filename, 'w')
o.write(self.write())
o.close() |
<SYSTEM_TASK:>
Write an arff structure to a string.
<END_TASK>
<USER_TASK:>
Description:
def write(self,
fout=None,
fmt=SPARSE,
schema_only=False,
data_only=False):
"""
Write an arff structure to a string.
""" |
assert not (schema_only and data_only), 'Make up your mind.'
assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s' % (fmt, ', '.join(FORMATS))
close = False
if fout is None:
close = True
fout = StringIO()
if not data_only:
print('% ' + re.sub("\n", "\n% ", '\n'.join(self.comment)), file=fout)
print("@relation " + self.relation, file=fout)
self.write_attributes(fout=fout)
if not schema_only:
print("@data", file=fout)
for d in self.data:
line_str = self.write_line(d, fmt=fmt)
if line_str:
print(line_str, file=fout)
if isinstance(fout, StringIO) and close:
return fout.getvalue() |
<SYSTEM_TASK:>
Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'.
<END_TASK>
<USER_TASK:>
Description:
def define_attribute(self, name, atype, data=None):
"""
Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'.
For nominal attributes, pass the possible values as data.
For date attributes, pass the format as data.
""" |
self.attributes.append(name)
assert atype in TYPES, "Unknown type '%s'. Must be one of: %s" % (atype, ', '.join(TYPES),)
self.attribute_types[name] = atype
self.attribute_data[name] = data |
<SYSTEM_TASK:>
Orders attributes names alphabetically, except for the class attribute, which is kept last.
<END_TASK>
<USER_TASK:>
Description:
def alphabetize_attributes(self):
"""
Orders attributes names alphabetically, except for the class attribute, which is kept last.
""" |
self.attributes.sort(key=lambda name: (name == self.class_attr_name, name)) |
<SYSTEM_TASK:>
Convert the color from RGB coordinates to CMY.
<END_TASK>
<USER_TASK:>
Description:
def rgb_to_cmy(r, g=None, b=None):
"""Convert the color from RGB coordinates to CMY.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (c, m, y) tuple in the range:
c[0...1],
m[0...1],
y[0...1]
>>> rgb_to_cmy(1, 0.5, 0)
(0, 0.5, 1)
""" |
if type(r) in [list,tuple]:
r, g, b = r
return (1-r, 1-g, 1-b) |
<SYSTEM_TASK:>
Convert the color from CMY coordinates to RGB.
<END_TASK>
<USER_TASK:>
Description:
def cmy_to_rgb(c, m=None, y=None):
"""Convert the color from CMY coordinates to RGB.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> cmy_to_rgb(0, 0.5, 1)
(1, 0.5, 0)
""" |
if type(c) in [list,tuple]:
c, m, y = c
return (1-c, 1-m, 1-y) |
<SYSTEM_TASK:>
Create a new instance based on this one but less saturated.
<END_TASK>
<USER_TASK:>
Description:
def desaturate(self, level):
"""Create a new instance based on this one but less saturated.
Parameters:
:level:
The amount by which the color should be desaturated to produce
the new one [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25)
Color(0.625, 0.5, 0.375, 1.0)
>>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25).hsl
(30.0, 0.25, 0.5)
""" |
h, s, l = self.__hsl
return Color((h, max(s - level, 0), l), 'hsl', self.__a, self.__wref) |
<SYSTEM_TASK:>
Return two colors analogous to this one.
<END_TASK>
<USER_TASK:>
Description:
def make_analogous_scheme(self, angle=30, mode='ryb'):
"""Return two colors analogous to this one.
Args:
:angle:
The angle between the hues of the created colors and this one.
:mode:
Select which color wheel to use for the generation (ryb/rgb).
Returns:
A tuple of grapefruit.Colors analogous to this one.
>>> c1 = Color.from_hsl(30, 1, 0.5)
>>> c2, c3 = c1.make_analogous_scheme(angle=60, mode='rgb')
>>> c2.hsl
(330.0, 1.0, 0.5)
>>> c3.hsl
(90.0, 1.0, 0.5)
>>> c2, c3 = c1.make_analogous_scheme(angle=10, mode='rgb')
>>> c2.hsl
(20.0, 1.0, 0.5)
>>> c3.hsl
(40.0, 1.0, 0.5)
""" |
h, s, l = self.__hsl
if mode == 'ryb': h = rgb_to_ryb(h)
h += 360
h1 = (h - angle) % 360
h2 = (h + angle) % 360
if mode == 'ryb':
h1 = ryb_to_rgb(h1)
h2 = ryb_to_rgb(h2)
return (Color((h1, s, l), 'hsl', self.__a, self.__wref),
Color((h2, s, l), 'hsl', self.__a, self.__wref)) |
<SYSTEM_TASK:>
Alpha-blend this color on the other one.
<END_TASK>
<USER_TASK:>
Description:
def alpha_blend(self, other):
"""Alpha-blend this color on the other one.
Args:
:other:
The grapefruit.Color to alpha-blend with this one.
Returns:
A grapefruit.Color instance which is the result of alpha-blending
this color on the other one.
>>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)
>>> c2 = Color.from_rgb(1, 1, 1, 0.8)
>>> c3 = c1.alpha_blend(c2)
>>> c3
Color(1.0, 0.875, 0.75, 0.84)
""" |
# get final alpha channel
fa = self.__a + other.__a - (self.__a * other.__a)
# get percentage of source alpha compared to final alpha
if fa==0: sa = 0
else: sa = min(1.0, self.__a/other.__a)
# destination percentage is just the additive inverse
da = 1.0 - sa
sr, sg, sb = [v * sa for v in self.__rgb]
dr, dg, db = [v * da for v in other.__rgb]
return Color((sr+dr, sg+dg, sb+db), 'rgb', fa, self.__wref) |
<SYSTEM_TASK:>
blend this color with the other one.
<END_TASK>
<USER_TASK:>
Description:
def blend(self, other, percent=0.5):
"""blend this color with the other one.
Args:
:other:
the grapefruit.Color to blend with this one.
Returns:
A grapefruit.Color instance which is the result of blending
this color on the other one.
>>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)
>>> c2 = Color.from_rgb(1, 1, 1, 0.6)
>>> c3 = c1.blend(c2)
>>> c3
Color(1.0, 0.75, 0.5, 0.4)
""" |
dest = 1.0 - percent
rgb = tuple(((u * percent) + (v * dest) for u, v in zip(self.__rgb, other.__rgb)))
a = (self.__a * percent) + (other.__a * dest)
return Color(rgb, 'rgb', a, self.__wref) |
<SYSTEM_TASK:>
Split query input into local files and URLs.
<END_TASK>
<USER_TASK:>
Description:
def split_input(args):
"""Split query input into local files and URLs.""" |
args['files'] = []
args['urls'] = []
for arg in args['query']:
if os.path.isfile(arg):
args['files'].append(arg)
else:
args['urls'].append(arg.strip('/')) |
<SYSTEM_TASK:>
Detect whether to save to a single or multiple files.
<END_TASK>
<USER_TASK:>
Description:
def detect_output_type(args):
"""Detect whether to save to a single or multiple files.""" |
if not args['single'] and not args['multiple']:
# Save to multiple files if multiple files/URLs entered
if len(args['query']) > 1 or len(args['out']) > 1:
args['multiple'] = True
else:
args['single'] = True |
<SYSTEM_TASK:>
Loads a trained classifier from the raw Weka model format.
<END_TASK>
<USER_TASK:>
Description:
def load_raw(cls, model_fn, schema, *args, **kwargs):
"""
Loads a trained classifier from the raw Weka model format.
Must specify the model schema and classifier name, since
these aren't currently deduced from the model format.
""" |
c = cls(*args, **kwargs)
c.schema = schema.copy(schema_only=True)
c._model_data = open(model_fn, 'rb').read()
return c |
<SYSTEM_TASK:>
Returns a ratio of classifiers that were able to be trained successfully.
<END_TASK>
<USER_TASK:>
Description:
def get_training_coverage(self):
"""
Returns a ratio of classifiers that were able to be trained successfully.
""" |
total = len(self.training_results)
i = sum(1 for data in self.training_results.values() if not isinstance(data, basestring))
return i/float(total) |
<SYSTEM_TASK:>
Get new links from a URL and filter them.
<END_TASK>
<USER_TASK:>
Description:
def get_new_links(self, url, resp):
"""Get new links from a URL and filter them.""" |
links_on_page = resp.xpath('//a/@href')
links = [utils.clean_url(u, url) for u in links_on_page]
# Remove non-links through filtering by protocol
links = [x for x in links if utils.check_protocol(x)]
# Restrict new URLs by the domain of the input URL
if not self.args['nonstrict']:
domain = utils.get_domain(url)
links = [x for x in links if utils.get_domain(x) == domain]
# Filter URLs by regex keywords, if any
if self.args['crawl']:
links = utils.re_filter(links, self.args['crawl'])
return links |
<SYSTEM_TASK:>
Check if page has been crawled by hashing its text content.
<END_TASK>
<USER_TASK:>
Description:
def page_crawled(self, page_resp):
"""Check if page has been crawled by hashing its text content.
Add new pages to the page cache.
Return whether page was found in cache.
""" |
page_text = utils.parse_text(page_resp)
page_hash = utils.hash_text(''.join(page_text))
if page_hash not in self.page_cache:
utils.cache_page(self.page_cache, page_hash, self.args['cache_size'])
return False
return True |
<SYSTEM_TASK:>
Find new links given a seed URL and follow them breadth-first.
<END_TASK>
<USER_TASK:>
Description:
def crawl_links(self, seed_url=None):
"""Find new links given a seed URL and follow them breadth-first.
Save page responses as PART.html files.
Return the PART.html filenames created during crawling.
""" |
if seed_url is not None:
self.seed_url = seed_url
if self.seed_url is None:
sys.stderr.write('Crawling requires a seed URL.\n')
return []
prev_part_num = utils.get_num_part_files()
crawled_links = set()
uncrawled_links = OrderedSet()
uncrawled_links.add(self.seed_url)
try:
while uncrawled_links:
# Check limit on number of links and pages to crawl
if self.limit_reached(len(crawled_links)):
break
url = uncrawled_links.pop(last=False)
# Remove protocol, fragments, etc. to get unique URLs
unique_url = utils.remove_protocol(utils.clean_url(url))
if unique_url not in crawled_links:
raw_resp = utils.get_raw_resp(url)
if raw_resp is None:
if not self.args['quiet']:
sys.stderr.write('Failed to parse {0}.\n'.format(url))
continue
resp = lh.fromstring(raw_resp)
if self.page_crawled(resp):
continue
crawled_links.add(unique_url)
new_links = self.get_new_links(url, resp)
uncrawled_links.update(new_links)
if not self.args['quiet']:
print('Crawled {0} (#{1}).'.format(url, len(crawled_links)))
# Write page response to PART.html file
utils.write_part_file(self.args, url, raw_resp, resp, len(crawled_links))
except (KeyboardInterrupt, EOFError):
pass
curr_part_num = utils.get_num_part_files()
return utils.get_part_filenames(curr_part_num, prev_part_num) |
<SYSTEM_TASK:>
Get available proxies to use with requests library.
<END_TASK>
<USER_TASK:>
Description:
def get_proxies():
"""Get available proxies to use with requests library.""" |
proxies = getproxies()
filtered_proxies = {}
for key, value in proxies.items():
if key.startswith('http://'):
if not value.startswith('http://'):
filtered_proxies[key] = 'http://{0}'.format(value)
else:
filtered_proxies[key] = value
return filtered_proxies |
<SYSTEM_TASK:>
Add a page to the page cache.
<END_TASK>
<USER_TASK:>
Description:
def cache_page(page_cache, page_hash, cache_size):
"""Add a page to the page cache.""" |
page_cache.append(page_hash)
if len(page_cache) > cache_size:
page_cache.pop(0) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.