text
stringlengths
81
112k
Makes a texture from a turtle program. Args: turtle_program (str): a string representing the turtle program; see the docstring of `branching_turtle_generator` for more details turn_amount (float): amount to turn in degrees initial_angle (float): initial orientation of the turtle...
Applies a given set of substitution rules to the given string or generator. For more background see: https://en.wikipedia.org/wiki/L-system Args: sequence (str): a string or generator onto which transformations are applied transformations (dict): a dictionary mapping each char to the strin...
Chains a transformation a given number of times. Args: sequence (str): a string or generator onto which transformations are applied transformations (dict): a dictionary mapping each char to the string that is substituted for it when the rule is applied iterations (int): how many...
Generates a texture by running transformations on a turtle program. First, the given transformations are applied to the axiom. This is repeated `iterations` times. Then, the output is run as a turtle program to get a texture, which is returned. For more background see: https://en.wikipedia.org/wiki/L-...
Returns the path corresponding to the node i. def get_path(self, i): """Returns the path corresponding to the node i.""" index = (i - 1) // 2 reverse = (i - 1) % 2 path = self.paths[index] if reverse: return path.reversed() else: return path
Returns the distance between the end of path i and the start of path j. def cost(self, i, j): """Returns the distance between the end of path i and the start of path j.""" return dist(self.endpoints[i][1], self.endpoints[j][0])
Returns the starting coordinates of node i as a pair, or the end coordinates iff end is True. def get_coordinates(self, i, end=False): """Returns the starting coordinates of node i as a pair, or the end coordinates iff end is True.""" if end: endpoint = self.endpoints[i][1] ...
Returns a generator over (index, start coordinate) pairs, excluding the origin. def iter_starts_with_index(self): """Returns a generator over (index, start coordinate) pairs, excluding the origin.""" for i in range(1, len(self.endpoints)): yield i, self.get_coordinates(i)
Returns a generator over 2-element lists of indexes which must be mutually exclusive in a solution (i.e. pairs of nodes which represent the same path in opposite directions.) def iter_disjunctions(self): """Returns a generator over 2-element lists of indexes which must be mutually exclu...
Preview a plot in a jupyter notebook. Args: plot (list): the plot to display (list of layers) width (int): the width of the preview height (int): the height of the preview Returns: An object that renders in Jupyter as the provided plot def show_plot(plot, width=PREVIEW_WID...
Calculates the size of the SVG viewBox to use. Args: layers (list): the layers in the image aspect_ratio (float): the height of the output divided by the width margin (float): minimum amount of buffer to add around the image, relative to the total dimensions Returns: ...
Generates an SVG path from a given layer. Args: layer (layer): the layer to convert Yields: str: the next component of the path def _layer_to_path_gen(layer): """Generates an SVG path from a given layer. Args: layer (layer): the layer to convert Yields: str: the ...
Converts a plot (list of layers) into an SVG document. Args: plot (list): list of layers that make up the plot width (float): the width of the resulting image height (float): the height of the resulting image unit (str): the units of the resulting image if not pixels Returns: ...
Writes a plot SVG to a file. Args: plot (list): a list of layers to plot filename (str): the name of the file to write width (float): the width of the output SVG height (float): the height of the output SVG unit (str): the unit of the height and width def write_plot(plot, f...
Draws a layer on the given matplotlib axis. Args: ax (axis): the matplotlib axis to draw on layer (layer): the layers to plot def draw_layer(ax, layer): """Draws a layer on the given matplotlib axis. Args: ax (axis): the matplotlib axis to draw on layer (layer): the layers...
Returns values on a surface for points on a texture. Args: texture (texture): the texture to trace over the surface surface (surface): the surface to trace along Returns: an array of surface heights for each point in the texture. Line separators (i.e. values that are ``nan`` in...
Creates a texture by adding z-values to an existing texture and projecting. When working with surfaces there are two ways to accomplish the same thing: 1. project the surface and map a texture to the projected surface 2. map a texture to the surface, and then project the result The first method, whic...
Returns the height of the surface when projected at the given angle. Args: surface (surface): the surface to project angle (float): the angle at which to project the surface Returns: surface: A projected surface. def project_surface(surface, angle=DEFAULT_ANGLE): """Returns the he...
Maps a texture onto a surface, then projects to 2D and returns a layer. Args: texture (texture): the texture to project surface (surface): the surface to project onto angle (float): the projection angle in degrees (0 = top-down, 90 = side view) Returns: layer: A layer. def pro...
Removes parts of a projected surface that are not visible. Args: projected_surface (surface): the surface to use Returns: surface: A projected surface. def _remove_hidden_parts(projected_surface): """Removes parts of a projected surface that are not visible. Args: projected_s...
Projects a texture onto a surface with occluded areas removed. Args: texture (texture): the texture to map to the projected surface surface (surface): the surface to project angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view) Returns: layer: A laye...
Makes a texture consisting of a given number of horizontal lines. Args: num_lines (int): the number of lines to draw resolution (int): the number of midpoints on each line Returns: A texture. def make_lines_texture(num_lines=10, resolution=50): """Makes a texture consisting of a g...
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. def...
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 alo...
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. def make_hex_texture(grid_size = 2, resolution=1): """M...
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. def make_noise_surface(dims=DE...
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. def make_gradients(dims=DEFAULT_DIMS): """Makes a pair of gradients to generate textures from numpy primitives. Args: ...
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. def make_sine_surface(dims=DEFAULT_DIMS, of...
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. def make_bubble_surf...
Solve a path using or-tools' Vehicle Routing Problem solver. Params: path_graph the PathGraph representing the problem initial_solution a solution to start with (list of indices, not including the origin) runtime_seconds how long to search before returning...
Initialize a controller. Provides a single global controller for applications that can't do this themselves def init_controller(url): """Initialize a controller. Provides a single global controller for applications that can't do this themselves """ # pylint: disable=global-statement g...
Perform a data_request and return the result. 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)
Get basic device info from Vera. 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)) i...
Search the list of connected devices by name. device_name param is the string name of the device 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 d...
Search the list of connected devices by ID. device_id param is the integer ID of the device 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 ...
Get list of connected devices. category_filter param is an array of strings 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 r...
Refresh data from Vera device. 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 = ...
Get full Vera device service info. 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': ...
Get data since last timestamp. This is done via a blocking call, pass NONE for initial state. 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: payloa...
Perfom a vera_request for this device. 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.d...
Set a variable on the vera device. This will call the Vera api to change device state. 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 = { ...
Call a Vera service. This will call the Vera api to change device state. def call_service(self, service_id, action): """Call a Vera service. This will call the Vera api to change device state. """ result = self.vera_request(id='action', serviceId=service_id, ...
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. def set_cache_value(self, name, value): """Set a variable in the local state dictionary. This ...
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. def set_cache_complex_value(self, name, value): """Set a variable in the local complex state di...
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. def get_complex_value(self, name): """Get a value from the service dictionaries. It's best to use get_value if it has the dat...
Get a case-sensitive keys value from the dev_info area. 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)
Refresh a value from the service dictionaries. It's best to use get_value / refresh if it has the data you need. 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 i...
Refresh the dev_info data used by get_value. Only needed if you're not using subscriptions. 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() ...
Update the dev_info data from a dictionary. Only updates if it already exists in the device. 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_i...
Get level from vera. 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: ...
Set the switch state, also update local state. 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', s...
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. def is_switched_on(self, refresh=False): """Get dimmer state. Refresh data from Vera if refresh is True, otherwise use loca...
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. def get_brightness(self, refres...
Set dimmer brightness. Converts the Vera level property for dimmable lights from a percentage to the 0 - 255 scale used by HA. def set_brightness(self, brightness): """Set dimmer brightness. Converts the Vera level property for dimmable lights from a percentage to the 0 - 255 ...
Get color index. Refresh data from Vera if refresh is True, otherwise use local cache. 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_v...
Get color. Refresh data from Vera if refresh is True, otherwise use local cache. 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') ...
Set dimmer color. def set_color(self, rgb): """Set dimmer color. """ target = ','.join([str(c) for c in rgb]) self.set_service_value( self.color_service, 'ColorRGB', 'newColorRGBTarget', target) rgbi = self.get_color_index(['R', ...
Set the armed state, also update local state. 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'...
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. def is_switched_on(self, refresh=False): """Get armed state. Refresh data from Vera if refresh is True, otherwise use local cache. R...
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. def is_open(self, refresh=False): """Get curtains state. Refresh data from Vera if refresh is True, otherwise use local cache. Re...
Set open level of the curtains. Scale is 0-100 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) ...
Get the last used PIN user id def get_last_user(self, refresh=False): """Get the last used PIN user id""" if refresh: self.refresh_complex_value('sl_UserCode') val = self.get_complex_value("sl_UserCode") # Syntax string: UserID="<pin_slot>" UserName="<pin_code_name>" ...
Get the list of PIN codes Codes can also be found with self.get_complex_value('PinCodes') 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...
Set current goal temperature / setpoint def set_temperature(self, temp): """Set current goal temperature / setpoint""" self.set_service_value( self.thermostat_setpoint, 'CurrentSetpoint', 'NewCurrentSetpoint', temp) self.set_cache_value('setpoin...
Get current goal temperature / setpoint def get_current_goal_temperature(self, refresh=False): """Get current goal temperature / setpoint""" if refresh: self.refresh() try: return float(self.get_value('setpoint')) except (TypeError, ValueError): retur...
Get current temperature def get_current_temperature(self, refresh=False): """Get current temperature""" if refresh: self.refresh() try: return float(self.get_value('temperature')) except (TypeError, ValueError): return None
Set the hvac mode def set_hvac_mode(self, mode): """Set the hvac mode""" self.set_service_value( self.thermostat_operating_service, 'ModeTarget', 'NewModeTarget', mode) self.set_cache_value('mode', mode)
Set the fan mode def set_fan_mode(self, mode): """Set the fan mode""" self.set_service_value( self.thermostat_fan_service, 'Mode', 'NewMode', mode) self.set_cache_value('fanmode', mode)
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. def get_last_scene_id(self, refresh=False): """Get last scene id. Refresh data from Vera if refresh is True, otherwise use local cache. ...
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. def get_last_scene_time(self, refresh=False): """Get last scene time. Refresh data from Vera if refresh is True, otherwise use local cac...
Perfom a vera_request for this scene. 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_...
Activate a Vera scene. This will call the Vera api to activate a scene. 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...
Refresh the data used by get_value. Only needed if you're not using subscriptions. 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...
Register a callback. device: device to be updated by subscription callback: callback for notification of changes def register(self, device, callback): """Register a callback. device: device to be updated by subscription callback: callback for notification of changes ""...
Remove a registered a callback. device: device that has the subscription callback: callback used in original registration def unregister(self, device, callback): """Remove a registered a callback. device: device that has the subscription callback: callback used in original reg...
Start a thread to handle Vera blocked polling. 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 s...
Format the UTC timestamp for Elasticsearch eg. 2014-07-09T08:37:18.000Z @see https://docs.python.org/2/library/time.html#time.strftime def format_timestamp(ts): """ Format the UTC timestamp for Elasticsearch eg. 2014-07-09T08:37:18.000Z @see https://docs.python.org/2/lib...
Choose between small, medium, large, ... depending on the amount specified. 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: ...
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 def format_tsv_line(source, edge, target, value=None, metadata=None): """ Render a single line for TSV file with data flow descri...
Render a .dot file with graph definition from a given set of data :type lines list[dict] :rtype: str 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 n...
:type logs str[] :type _map (list) -> str :type _reduce (list) -> obj def logs_map_and_reduce(logs, _map, _reduce): """ :type logs str[] :type _map (list) -> str :type _reduce (list) -> obj """ keys = [] mapped_count = Counter() mapped = defaultdict(list) # first map all en...
Close the remote chromium instance. This command is normally executed as part of the class destructor. It can be called early without issue, but calling ANY class functions after the remote chromium instance is shut down will have unknown effects. Note that if you are rapidly creating and destroying ChromeCon...
Open a websocket connection to remote browser, determined by self.host and self.port. Each tab has it's own websocket endpoint. 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 ...
Close websocket connection to remote browser. 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)
Connect to host:port and request list of tabs return list of dicts of data about open tabs. def fetch_tablist(self): """Connect to host:port and request list of tabs return list of dicts of data about open tabs.""" # find websocket endpoint try: response = requests.get("http://%s:%s/json" % (self.host...
Synchronously execute command `command` with params `params` in the remote chrome instance, returning the response from the chrome instance. def synchronous_command(self, command, tab_key, **params): """ Synchronously execute command `command` with params `params` in the remote chrome instance, returning the r...
Send command `command` with optional parameters `params` to the remote chrome instance. The command `id` is automatically added to the outgoing message. return value is the command id, which can be used to match a command to it's associated response. def send(self, command, tab_key, params=None): ''' Sen...
Receive a filtered message, using the callable `keycheck` to filter received messages for content. `keycheck` is expected to be a callable that takes a single parameter (the decoded response from chromium), and returns a boolean (true, if the command is the one filtered for, or false if the command is not the ...
Receive a all messages matching a filter, using the callable `keycheck` to filter received messages for content. This function will *ALWAY* block for at least `timeout` seconds. If chromium is for some reason continuously streaming responses, it may block forever! `keycheck` is expected to be a callable that...
Recieve a message, optionally filtering for a specified message id. If `message_id` is none, the first command in the receive queue is returned. If `message_id` is not none, the command waits untill a message is received with the specified id, or it times out. Timeout is the number of seconds to wait for a re...
Return all messages in waiting for the websocket connection. def drain(self, tab_key): ''' Return all messages in waiting for the websocket connection. ''' self.log.debug("Draining transport") ret = [] while len(self.messages[tab_key]): ret.append(self.messages[tab_key].pop(0)) self.log.debug("Pollin...
ChromeController \b Usage: python3 -m ChromeController [-s | --silent] [-v | --verbose] python3 -m ChromeController fetch <url> [--binary <bin_name>] [--outfile <out_file_name>] python3 -m ChromeController update python3 -m ChromeController (-h | --help) python3 -m ChromeController --version \b Options: -s ...
Fetch a specified URL's content, and output it to the console. def fetch(url, binary, outfile, noprint, rendered): ''' Fetch a specified URL's content, and output it to the console. ''' with chrome_context.ChromeContext(binary=binary) as cr: resp = cr.blocking_navigate_and_get_source(url) if rendered: resp[...
Function path: Memory.setPressureNotificationsSuppressed Domain: Memory Method name: setPressureNotificationsSuppressed Parameters: Required arguments: 'suppressed' (type: boolean) -> If true, memory pressure notifications will be suppressed. No return value. Description: Enable/disable su...
Function path: Page.addScriptToEvaluateOnLoad Domain: Page Method name: addScriptToEvaluateOnLoad WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'scriptSource' (type: string) -> No description Returns: 'identifier' (type: ScriptIdentifier) -> Identifie...
Function path: Page.addScriptToEvaluateOnNewDocument Domain: Page Method name: addScriptToEvaluateOnNewDocument WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'source' (type: string) -> No description Returns: 'identifier' (type: ScriptIdentifier) -> I...
Function path: Page.setAutoAttachToCreatedPages Domain: Page Method name: setAutoAttachToCreatedPages WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'autoAttach' (type: boolean) -> If true, browser will open a new inspector window for every page created from ...
Function path: Page.setAdBlockingEnabled Domain: Page Method name: setAdBlockingEnabled WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'enabled' (type: boolean) -> Whether to block ads. No return value. Description: Enable Chrome's experimental ad fi...
Function path: Page.navigateToHistoryEntry Domain: Page Method name: navigateToHistoryEntry WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'entryId' (type: integer) -> Unique id of the entry to navigate to. No return value. Description: Navigates cur...
Function path: Page.deleteCookie Domain: Page Method name: deleteCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'cookieName' (type: string) -> Name of the cookie to remove. 'url' (type: string) -> URL to match cooke domain and path. No return v...