output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def main():
"""Filters the document AST."""
# pylint: disable=global-statement
global PANDOCVERSION
global AttrTable
# Get the output format and document
fmt = args.fmt
doc = json.loads(STDIN.read())
# Initialize pandocxnos
# pylint: disable=too-many-function-args
PANDOCVERSIO... | How would you code a function in Python 3 to
filter the document AST and returns the resulting XML tree. | You are a Python code generator, capable of creating scripts from specifications. |
Make a http request to the clockwork server | Given the following Python 3 function, write the documentation
def request(url, xml):
r = _urllib.Request(url, xml)
r.add_header('Content-Type', 'application/xml')
r.add_header('User-Agent', 'Clockwork Python wrapper/1.0')
result = {}
try:
f = _urllib.urlopen(r)
except URLError... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_balance(self):
"""Check the balance fot this account.
Returns a dictionary containing:
account_type: The account type
balance: The balance remaining on the account
currency: The currency used for the account balance. Assume GBP in not set"""
xml_root ... | How would you code a function in Python 3 to
check the balance fot this account. | You are a Python code generator, capable of creating scripts from specifications. |
Send a list of SMS messages or an array of SMS messages | Explain what the following Python 3 code does
def send(self, messages):
tmpSms = SMS(to='', message='')
if str(type(messages)) == str(type(tmpSms)):
messages = [messages]
xml_root = self.__init_xml('Message')
wrapper_id = 0
for m in messages:
m.wrapper_... | As a Python code analyst, you investigate and solve complex coding mysteries |
Init a etree element and pop a key in there | Given the following Python 3 function, write the documentation
def __init_xml(self, rootElementTag):
xml_root = etree.Element(rootElementTag)
key = etree.SubElement(xml_root, "Key")
key.text = self.apikey
return xml_root | You are a Python code architect, reviewing and designing scalable and efficient code |
Build a dictionary of SMS message elements | Can you generate a brief explanation for the following Python 3 code
def __build_sms_data(self, message):
attributes = {}
attributes_to_translate = {
'to' : 'To',
'message' : 'Content',
'client_id' : 'ClientID',
'concat' : 'Concat',
'from_nam... | You are a Python code generator, capable of creating scripts from specifications. |
Convert serialized pstats to a list of raw entries. | How would you explain what the following Python 3 function does
def pstats2entries(data):
# Each entry's key is a tuple of (filename, line number, function name)
entries = {}
allcallers = {}
# first pass over stats to build the list of entry instances
for code_info, call_info in data.stats.items():... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return whether or not a given executable is installed on the machine. | Explain what the following Python 3 code does
def is_installed(prog):
with open(os.devnull, 'w') as devnull:
try:
if os.name == 'nt':
retcode = subprocess.call(['where', prog], stdout=devnull)
else:
retcode = subprocess.call(['which', prog], stdout=dev... | As a Python code composer, you craft elegant and concise scripts. |
def main():
"""Execute the converter using parameters provided on the command line"""
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--outfile', metavar='output_file_path',
help="Save calltree stats to <outfile>")
parser.add_argument('-i', '--infile', metavar='inp... | Can you write a function in Python 3 where it
executes the kcachegrind tool on the calltree. | As a Python code analyst, you investigate and solve complex coding mysteries |
convert profiling_data to calltree format and dump it to outputfile | Can you generate the documentation for the following Python 3 function
def convert(profiling_data, outputfile):
converter = CalltreeConverter(profiling_data)
if is_basestring(outputfile):
with open(outputfile, "w") as f:
converter.output(f)
else:
converter.output(outputfile) | You are a Python code architect, reviewing and designing scalable and efficient code |
Write the converted entries to out_file | Given the following Python 3 function, write the documentation
def output(self, out_file):
self.out_file = out_file
out_file.write('event: ns : Nanoseconds\n')
out_file.write('events: ns\n')
self._output_summary()
for entry in sorted(self.entries, key=_entry_sort_key):
... | You are a Python code generator, capable of creating scripts from specifications. |
def visualize(self):
"""Launch kcachegrind on the converted entries.
One of the executables listed in KCACHEGRIND_EXECUTABLES
must be present in the system path.
"""
available_cmd = None
for cmd in KCACHEGRIND_EXECUTABLES:
if is_installed(cmd):
... | Create a Python 3 function to
launch kcachegrind on the converted entries. | As a Python code analyst, you investigate and solve complex coding mysteries |
Helper method that implements the logic to look up an application. | Here you have a function in Python 3, explain what it does
def get_app(self, reference_app=None):
if reference_app is not None:
return reference_app
if self.app is not None:
return self.app
ctx = stack.top
if ctx is not None:
return ctx.app
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def init_app(self, app, **kwargs):
""" Initializes the Flask-Bouncer extension for the specified application.
:param app: The application.
"""
self.app = app
self._init_extension()
self.app.before_request(self.check_implicit_rules)
if kwargs.get('ensure_author... | How would you implement a function in Python 3 that
initializes the Flask - Bouncer extension for the specified application. | As a Python code analyst, you investigate and solve complex coding mysteries |
checks that an authorization call has been made during the request | Here you have a function in Python 3, explain what it does
def check_authorization(self, response):
if not hasattr(request, '_authorized'):
raise Unauthorized
elif not request._authorized:
raise Unauthorized
return response | You are a Python code architect, reviewing and designing scalable and efficient code |
Check implicit rules for the current user. | Can you tell what is the following Python 3 function doing
def check_implicit_rules(self):
if not self.request_is_managed_by_flask_classy():
return
if self.method_is_explictly_overwritten():
return
class_name, action = request.endpoint.split(':')
clazz = [classy... | As a python code expert, you are capable of creating scripts from specifications. |
Rotates the given texture by a given angle. | Can you generate a brief explanation for the following Python 3 code
def rotate_texture(texture, rotation, x_offset=0.5, y_offset=0.5):
x, y = texture
x = x.copy() - x_offset
y = y.copy() - y_offset
angle = np.radians(rotation)
x_rot = x * np.cos(angle) + y * np.sin(angle)
y_rot = x * -np.sin(an... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Fits a layer into a texture by scaling each axis to 0 1. | Can you generate a brief explanation for the following Python 3 code
def fit_texture(layer):
x, y = layer
x = (x - np.nanmin(x)) / (np.nanmax(x) - np.nanmin(x))
y = (y - np.nanmin(y)) / (np.nanmax(y) - np.nanmin(y))
return x, y | You are a Python code generator, capable of creating scripts from specifications. |
Check that the solution is valid. | Can you tell what is the following Python 3 function doing
def check_valid_solution(solution, graph):
expected = Counter(
i for (i, _) in graph.iter_starts_with_index()
if i < graph.get_disjoint(i)
)
actual = Counter(
min(i, graph.get_disjoint(i))
for i in solution
)
... | You are a Python code generator, capable of creating scripts from specifications. |
def get_route_from_solution(solution, graph):
"""Converts a solution (a list of node indices) into a list
of paths suitable for rendering."""
# As a guard against comparing invalid "solutions",
# ensure that this solution is valid.
assert check_valid_solution(solution, graph)
return [graph.get... | Can you create a Python 3 function that
converts a solution into a list of paths suitable for rendering. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generates a generator of turtle positions and lines that are branched at each location. | Can you generate the documentation for the following Python 3 function
def branching_turtle_generator(turtle_program, turn_amount=DEFAULT_TURN,
initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
"""Given a turtle program, creates a generator of turtle positions.
The state of... | As a Python code analyst, you investigate and solve complex coding mysteries |
def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN,
initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
"""Makes a texture from a turtle program.
Args:
turtle_program (str): a string representing the turtle program; see the
docstring of `branching_turtle_ge... | Write a Python 3 function for
making a texture from a turtle program. | You are a Python code architect, reviewing and designing scalable and efficient code |
Applies a given set of substitution rules to the given string or generator. | Explain what the following Python 3 code does
def transform_sequence(sequence, transformations):
for c in sequence:
for k in transformations.get(c, c):
yield k | As a python code expert, you are capable of creating scripts from specifications. |
def transform_multiple(sequence, transformations, iterations):
"""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
substitu... | Implement a Python 3 function for
chaining a transformation a given number of times. | As a Python code analyst, you investigate and solve complex coding mysteries |
def l_system(axiom, transformations, iterations=1, angle=45, resolution=1):
"""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... | How would you code a function in Python 3 to
generate a texture by running transformations on a turtle program that is a turtle system. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the path corresponding to the node i. | Explain what the following Python 3 code does
def get_path(self, i):
index = (i - 1) // 2
reverse = (i - 1) % 2
path = self.paths[index]
if reverse:
return path.reversed()
else:
return path | As a python code expert, you are capable of creating scripts from specifications. |
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]) | Implement a function in Python 3 to
return the distance between the end of path i and the start of path j. | You are a Python code analyst, evaluating scripts for potential improvements. |
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]
else:
endpoint = self.endpoints[i][0]
return (endpoint.real, endpoint.imag) | Can you create a Python 3 function that
returns the starting coordinates of node i as a pair and the end coordinates iff end is True. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a generator over ( index start coordinate ) pairs and the original location of the resource. | How would you explain what the following Python 3 function does
def iter_starts_with_index(self):
for i in range(1, len(self.endpoints)):
yield i, self.get_coordinates(i) | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns an iterator over the disjoints of the cluster - level entries. | Here you have a function in Python 3, explain what it does
def iter_disjunctions(self):
for i in range(1, len(self.endpoints), 2):
yield [i, self.get_disjoint(i)] | You are a Python code architect, reviewing and designing scalable and efficient code |
def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT):
"""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 render... | Create a Python 3 function for
previewing a plot in a jupyter notebook. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Calculates the size of the SVG viewBox to use. | Can you generate the documentation for the following Python 3 function
def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN):
min_x = min(np.nanmin(x) for x, y in layers)
max_x = max(np.nanmax(x) for x, y in layers)
min_y = min(np.nanmin(y) for x, y in layers)
max_y = max(np.nanma... | As a python code expert, you are capable of creating scripts from specifications. |
def _layer_to_path_gen(layer):
"""Generates an SVG path from a given layer.
Args:
layer (layer): the layer to convert
Yields:
str: the next component of the path
"""
draw = False
for x, y in zip(*layer):
if np.isnan(x) or np.isnan(y):
draw = False
el... | Create a Python 3 function for
generating an SVG path from a given layer. | You are a Python code architect, reviewing and designing scalable and efficient code |
def plot_to_svg(plot, width, height, unit=''):
"""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 unit... | Create a Python 3 function to
convert a list of layers into an SVG document. | As a Python code analyst, you investigate and solve complex coding mysteries |
Writes a plot SVG to a file. | Can you tell what is the following Python 3 function doing
def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT):
svg = plot_to_svg(plot, width, height, unit)
with open(filename, 'w') as outfile:
outfile.write(svg) | You are a Python code generator, capable of creating scripts from specifications. |
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 to plot
"""
ax.set_aspect('equal', 'datalim')
ax.plot(*layer)
ax.axis('off') | Write a Python 3 function that can
draw a layer on the given matplotlib axis. | As a Python code composer, you craft elegant and concise scripts. |
Returns the values on a surface for each point in the specified texture. | Explain what the following Python 3 code does
def map_texture_to_surface(texture, surface):
texture_x, texture_y = texture
surface_h, surface_w = surface.shape
surface_x = np.clip(
np.int32(surface_w * texture_x - 1e-9), 0, surface_w - 1)
surface_y = np.clip(
np.int32(surface_h * textur... | You are a Python code analyst, evaluating scripts for potential improvements. |
def project_texture(texture_xy, texture_z, angle=DEFAULT_ANGLE):
"""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... | Can you create a Python 3 function that
creates a new texture by adding z - values to an existing texture and projecting it. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def project_surface(surface, angle=DEFAULT_ANGLE):
"""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.
"""
z_c... | Can you implement a function in Python 3 that
returns the height of the surface when projected at the given angle. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE):
"""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... | Write a Python 3 script to
map a texture onto a surface then projects it onto a 2D layer. | You are a Python code generator, capable of creating scripts from specifications. |
def _remove_hidden_parts(projected_surface):
"""Removes parts of a projected surface that are not visible.
Args:
projected_surface (surface): the surface to use
Returns:
surface: A projected surface.
"""
surface = np.copy(projected_surface)
surface[~_make_occlusion_mask(project... | Write a Python 3 script to
remove hidden parts from a projected surface. | You are a Python code generator, capable of creating scripts from specifications. |
def project_and_occlude_texture(texture, surface, angle=DEFAULT_ANGLE):
"""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... | Can you write a function in Python 3 where it
projects a texture onto a surface with occluded areas removed. | You are a Python code generator, capable of creating scripts from specifications. |
def make_lines_texture(num_lines=10, resolution=50):
"""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.
"""
x, y = np.meshgrid(
... | Can you write a function in Python 3 where it
makes a texture consisting of a given number of horizontal lines. | You are a Python code architect, reviewing and designing scalable and efficient code |
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 n... | How would you code a function in Python 3 to
make a texture consisting of a grid of horizontal and vertical lines. | You are a Python code architect, reviewing and designing scalable and efficient code |
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, ... | Implement a function in Python 3 to
make a texture consisting of a spiral from the origin. | You are a Python code analyst, evaluating scripts for potential improvements. |
Makes a texture consisting on a grid of hexagons. | Explain what the following Python 3 code does
def make_hex_texture(grid_size = 2, resolution=1):
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)... | You are a Python code analyst, evaluating scripts for potential improvements. |
Makes a random noise surface | Explain what the following Python 3 code does
def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None):
if seed is not None:
np.random.seed(seed)
return gaussian_filter(np.random.normal(size=dims), blur) | You are a Python code architect, reviewing and designing scalable and efficient code |
Makes a pair of gradients to generate textures from numpy primitives. | Here you have a function in Python 3, explain what it does
def make_gradients(dims=DEFAULT_DIMS):
return np.meshgrid(
np.linspace(0.0, 1.0, dims[0]),
np.linspace(0.0, 1.0, dims[1])
) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Makes a surface from the 3D sine function. | How would you explain what the following Python 3 function does
def make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0):
gradients = (np.array(make_gradients(dims)) - offset) * scale * np.pi
return np.sin(np.linalg.norm(gradients, axis=0)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Makes a surface from the product of sine functions on each axis. | Can you generate a brief explanation for the following Python 3 code
def make_bubble_surface(dims=DEFAULT_DIMS, repeat=3):
gradients = make_gradients(dims)
return (
np.sin((gradients[0] - 0.5) * repeat * np.pi) *
np.sin((gradients[1] - 0.5) * repeat * np.pi)) | You are a Python code analyst, evaluating scripts for potential improvements. |
Solve a path using or - tools Vehicle Routing Problem solver. | Make a summary of the following Python 3 code
def vrp_solver(path_graph, initial_solution=None, runtime_seconds=60):
# Create the VRP routing model. The 1 means we are only looking
# for a single path.
routing = pywrapcp.RoutingModel(path_graph.num_nodes(),
1, path_graph.... | As a python code expert, you are capable of creating scripts from specifications. |
Initialize a controller.
Provides a single global controller for applications that can't do this
themselves | Make a summary of the following Python 3 code
def init_controller(url):
# 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_CONTROL... | You are a Python code analyst, evaluating scripts for potential improvements. |
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) | Create a Python 3 function to
perform a data_request and return the result. | You are a Python code generator, capable of creating scripts from specifications. |
Get basic device info from Vera. | Make a summary of the following Python 3 code
def get_simple_devices_info(self):
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'):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
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():
... | Write a Python 3 script to
search the list of connected devices by name. | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | How would you code a function in Python 3 to
search the list of connected devices by ID. | You are a Python code analyst, evaluating scripts for potential improvements. |
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_... | Create a Python 3 function to
get list of connected devices. | As a Python code analyst, you investigate and solve complex coding mysteries |
Refresh data from Vera device. | Can you generate the documentation for the following Python 3 function
def refresh_data(self):
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(... | As a python code expert, you are capable of creating scripts from specifications. |
Get full Vera device service info. | Can you tell what is the following Python 3 function doing
def map_services(self):
# 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()
s... | You are a Python code analyst, evaluating scripts for potential improvements. |
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,
... | Implement a function in Python 3 to
get data since last timestamp. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set a variable on the vera device. | Can you generate the documentation for the following Python 3 function
def set_service_value(self, service_id, set_name, parameter_name, value):
payload = {
'id': 'lu_action',
'action': 'Set' + set_name,
'serviceId': service_id,
parameter_name: value
}
... | As a Python code composer, you craft elegant and concise scripts. |
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,
action=action)
logger.debug("call_service: "
... | Create a Python 3 function to
call a Vera service. | You are a Python code architect, reviewing and designing scalable and efficient code |
Set a variable in the local state dictionary. | Given the following Python 3 function, write the documentation
def set_cache_value(self, name, value):
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)
... | As a Python code composer, you craft elegant and concise scripts. |
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_sta... | Write a Python 3 script to
set a variable in the local complex state dictionary. | As a Python code composer, you craft elegant and concise scripts. |
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'... | Can you create a Python 3 function that
gets a value from the service dictionaries. | You are a Python code analyst, evaluating scripts for potential improvements. |
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) | Write a Python 3 function for
getting a case - sensitive key value from the dev_info area. | You are a Python code architect, reviewing and designing scalable and efficient code |
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('s... | Write a Python 3 function for
refreshing a value from the service dictionaries. | As a python code expert, you are capable of creating scripts from specifications. |
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'... | Write a Python 3 function for
refreshing the dev_info data used by get_value. | As a python code expert, you are capable of creating scripts from specifications. |
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)}) | Can you implement a function in Python 3 that
updates the dev_info data from a dictionary. | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Write a Python 3 script to
get level from vera. | You are a Python code analyst, evaluating scripts for potential improvements. |
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) | Write a Python 3 function that can
set the switch state also update local state. | As a Python code analyst, you investigate and solve complex coding mysteries |
Check if dimmer is switched on. | Explain what the following Python 3 code does
def is_switched_on(self, refresh=False):
if refresh:
self.refresh()
return self.get_brightness(refresh) > 0 | You are a Python code architect, reviewing and designing scalable and efficient code |
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 - 25... | Create a Python 3 function for
getting dimmer brightness from Vera level property. | As a Python code composer, you craft elegant and concise scripts. |
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_ser... | Can you implement a function in Python 3 that
sets dimmer brightness. Converts the Vera level property for dimmable lights from a percentage to the 0 - 255 scale used by HA. | You are a Python code architect, reviewing and designing scalable and efficient code |
Get color index.
Refresh data from Vera if refresh is True, otherwise use local cache. | Given the following Python 3 function, write the documentation
def get_color_index(self, colors, refresh=False):
if refresh:
self.refresh_complex_value('SupportedColors')
sup = self.get_complex_value('SupportedColors')
if sup is None:
return None
sup = sup.split... | As a python code expert, you are capable of creating scripts from specifications. |
Get color.
Refresh data from Vera if refresh is True, otherwise use local cache. | Here you have a function in Python 3, explain what it does
def get_color(self, refresh=False):
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... | You are a Python code analyst, evaluating scripts for potential improvements. |
Set the armed state also update local state. | Here you have a function in Python 3, explain what it does
def set_armed_state(self, state):
self.set_service_value(
self.security_sensor_service,
'Armed',
'newArmedValue',
state)
self.set_cache_value('Armed', state) | As a Python code composer, you craft elegant and concise scripts. |
Check if the user is armed on. | How would you explain what the following Python 3 function does
def is_switched_on(self, refresh=False):
if refresh:
self.refresh()
val = self.get_value('Armed')
return val == '1' | As a Python code analyst, you investigate and solve complex coding mysteries |
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 | Implement a function in Python 3 to
check if the current state of the current instance is open. | As a python code expert, you are capable of creating scripts from specifications. |
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) | Implement a Python 3 function for
setting the open level of the curtains. | You are a Python code generator, capable of creating scripts from specifications. |
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>"
# See http://wiki.micasaverde.... | Create a Python 3 function for
getting the last used PIN user id | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the list of PIN codes that can be found with self. get_complex_value ( PIN_CODES ) | Can you generate a brief explanation for the following Python 3 code
def get_pin_codes(self, refresh=False):
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,nam... | You are a Python code generator, capable of creating scripts from specifications. |
Set current goal temperature | How would you explain what the following Python 3 function does
def set_temperature(self, temp):
self.set_service_value(
self.thermostat_setpoint,
'CurrentSetpoint',
'NewCurrentSetpoint',
temp)
self.set_cache_value('setpoint', temp) | You are a Python code analyst, evaluating scripts for potential improvements. |
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):
return None | Write a Python 3 function for
getting current goal temperature | You are a Python code analyst, evaluating scripts for potential improvements. |
Set the hvac mode | Can you generate the documentation for the following Python 3 function
def set_hvac_mode(self, mode):
self.set_service_value(
self.thermostat_operating_service,
'ModeTarget',
'NewModeTarget',
mode)
self.set_cache_value('mode', mode) | You are a Python code generator, capable of creating scripts from specifications. |
Set the fan mode | Can you generate a brief explanation for the following Python 3 code
def set_fan_mode(self, mode):
self.set_service_value(
self.thermostat_fan_service,
'Mode',
'NewMode',
mode)
self.set_cache_value('fanmode', mode) | As a Python code composer, you craft elegant and concise scripts. |
Get the last scene id from Vera. | Given the following Python 3 function, write the documentation
def get_last_scene_id(self, refresh=False):
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... | As a Python code composer, you craft elegant and concise scripts. |
Get last scene time from Vera | Make a summary of the following Python 3 code
def get_last_scene_time(self, refresh=False):
if refresh:
self.refresh_complex_value('LastSceneTime')
val = self.get_complex_value('LastSceneTime')
return val | You are a Python code generator, capable of creating scripts from specifications. |
Perfom a vera_request for this scene. | Explain what the following Python 3 code does
def vera_request(self, **kwargs):
request_payload = {
'output_format': 'json',
'SceneNum': self.scene_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) | As a python code expert, you are capable of creating scripts from specifications. |
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)
log... | Can you create a Python 3 function that
activates a Vera scene. | You are a Python code analyst, evaluating scripts for potential improvements. |
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.scen... | How would you code a function in Python 3 to
refresh the data used by get_value. | As a python code expert, you are capable of creating scripts from specifications. |
def register(self, device, callback):
"""Register a callback.
device: device to be updated by subscription
callback: callback for notification of changes
"""
if not device:
logger.error("Received an invalid device: %r", device)
return
logger.debu... | Implement a function in Python 3 to
register a callback for a specific device. | You are a Python code analyst, evaluating scripts for potential improvements. |
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
... | Create a Python 3 function for
removing a registered callback. | As a Python code composer, you craft elegant and concise scripts. |
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() | How would you code a function in Python 3 to
start a thread to handle Vera blocked polling. | As a Python code analyst, you investigate and solve complex coding mysteries |
Format the UTC timestamp for Elasticsearch
eg. 2014 - 07 - 09T08 : 37.000Z | Make a summary of the following Python 3 code
def format_timestamp(ts):
tz_info = tz.tzutc()
return datetime.fromtimestamp(ts, tz=tz_info).strftime("%Y-%m-%dT%H:%M:%S.000Z") | As a Python code translator, you convert algorithms and pseudocode into Python. |
Choose the level of the item based on the amount specified. | How would you explain what the following Python 3 function does
def _pick_level(cls, btc_amount):
for size, level in cls.TICKER_LEVEL:
if btc_amount < size:
return level
return cls.TICKER_LEVEL[-1][1] | As a python code expert, you are capable of creating scripts from specifications. |
Render a single line for TSV file with data flow described by the user. | Can you generate the documentation for the following Python 3 function
def format_tsv_line(source, edge, target, value=None, metadata=None):
return '{source}\t{edge}\t{target}\t{value}\t{metadata}'.format(
source=source,
edge=edge,
target=target,
value='{:.4f}'.format(value) if value... | You are a Python code generator, capable of creating scripts from specifications. |
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... | Write a Python 3 script to
render a. dot file with graph definition from a given set of data. | As a Python code translator, you convert algorithms and pseudocode into Python. |
map and reduce the log list | Here you have a function in Python 3, explain what it does
def logs_map_and_reduce(logs, _map, _reduce):
keys = []
mapped_count = Counter()
mapped = defaultdict(list)
# first map all entries
for log in logs:
key = _map(log)
mapped[key].append(log)
mapped_count[key] += 1
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def close_chromium(self):
'''
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... | Can you create a Python 3 function that
closes 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 cr... | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.