INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr)
def _interfaces_ip(out): """ Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) """ ret = dict() def parse_network(value, cols): """ Return a tuple of ip, netmask, broadcast based on the current set of cols """ brd = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr return (ip, mask, brd) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret
Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr)
def _interfaces_ifconfig(out): """ Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) """ ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') pip = re.compile(r'.*?(?:inet addr:|inet )(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+)).*') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret
From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string.
def get_chacra_repo(shaman_url): """ From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string. """ shaman_response = get_request(shaman_url) chacra_url = shaman_response.geturl() chacra_response = get_request(chacra_url) return chacra_response.read()
Returns a list of packages to install based on component names This is done by checking if a component is in notsplit_packages, if it is, we know we need to install 'ceph' instead of the raw component name. Essentially, this component hasn't been 'split' from the master 'ceph' package yet.
def map_components(notsplit_packages, components): """ Returns a list of packages to install based on component names This is done by checking if a component is in notsplit_packages, if it is, we know we need to install 'ceph' instead of the raw component name. Essentially, this component hasn't been 'split' from the master 'ceph' package yet. """ packages = set() for c in components: if c in notsplit_packages: packages.add('ceph') else: packages.add(c) return list(packages)
start mon service depending on distro init
def start_mon_service(distro, cluster, hostname): """ start mon service depending on distro init """ if distro.init == 'sysvinit': service = distro.conn.remote_module.which_service() remoto.process.run( distro.conn, [ service, 'ceph', '-c', '/etc/ceph/{cluster}.conf'.format(cluster=cluster), 'start', 'mon.{hostname}'.format(hostname=hostname) ], timeout=7, ) system.enable_service(distro.conn) elif distro.init == 'upstart': remoto.process.run( distro.conn, [ 'initctl', 'emit', 'ceph-mon', 'cluster={cluster}'.format(cluster=cluster), 'id={hostname}'.format(hostname=hostname), ], timeout=7, ) elif distro.init == 'systemd': # enable ceph target for this host (in case it isn't already enabled) remoto.process.run( distro.conn, [ 'systemctl', 'enable', 'ceph.target' ], timeout=7, ) # enable and start this mon instance remoto.process.run( distro.conn, [ 'systemctl', 'enable', 'ceph-mon@{hostname}'.format(hostname=hostname), ], timeout=7, ) remoto.process.run( distro.conn, [ 'systemctl', 'start', 'ceph-mon@{hostname}'.format(hostname=hostname), ], timeout=7, )
Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : list of tuples Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end.
def __voronoi_finite_polygons_2d(vor, radius=None): """ Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : list of tuples Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end. """ if vor.points.shape[1] != 2: raise ValueError("Requires 2D input") new_regions = [] new_vertices = vor.vertices.tolist() center = vor.points.mean(axis=0) if radius is None: radius = vor.points.ptp().max() # Construct a map containing all ridges for a given point all_ridges = {} for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices): all_ridges.setdefault(p1, []).append((p2, v1, v2)) all_ridges.setdefault(p2, []).append((p1, v1, v2)) # Reconstruct infinite regions for p1, region in enumerate(vor.point_region): vertices = vor.regions[region] if all(v >= 0 for v in vertices): # finite region new_regions.append(vertices) continue # reconstruct a non-finite region if p1 not in all_ridges: continue ridges = all_ridges[p1] new_region = [v for v in vertices if v >= 0] for p2, v1, v2 in ridges: if v2 < 0: v1, v2 = v2, v1 if v1 >= 0: # finite ridge: already in the region continue # Compute the missing endpoint of an infinite ridge t = vor.points[p2] - vor.points[p1] # tangent t /= np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = vor.points[[p1, p2]].mean(axis=0) direction = np.sign(np.dot(midpoint - center, n)) * n far_point = vor.vertices[v2] + direction * radius new_region.append(len(new_vertices)) new_vertices.append(far_point.tolist()) # sort region counterclockwise vs = np.asarray([new_vertices[v] for v in new_region]) c = vs.mean(axis=0) angles = np.arctan2(vs[:,1] - c[1], vs[:,0] - c[0]) new_region = np.array(new_region)[np.argsort(angles)] # finish new_regions.append(new_region.tolist()) return new_regions, np.asarray(new_vertices)
display the map inline in ipython :param width: image width for the browser
def inline(width=900): """display the map inline in ipython :param width: image width for the browser """ from IPython.display import Image, HTML, display, clear_output import random import string import urllib import os while True: fname = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32)) if not os.path.isfile(fname + '.png'): break savefig(fname) if os.path.isfile(fname + '.png'): with open(fname + '.png', 'rb') as fin: encoded = base64.b64encode(fin.read()) b64 = urllib.parse.quote(encoded) image_html = "<img style='width: %dpx; margin: 0px; float: left; border: 1px solid black;' src='data:image/png;base64,%s' />" % (width, b64) display(HTML(image_html)) os.remove(fname + '.png')
Create a dot density map :param data: data access object :param color: color :param point_size: point size :param f_tooltip: function to return a tooltip string for a point
def dot(data, color=None, point_size=2, f_tooltip=None): """Create a dot density map :param data: data access object :param color: color :param point_size: point size :param f_tooltip: function to return a tooltip string for a point """ from geoplotlib.layers import DotDensityLayer _global_config.layers.append(DotDensityLayer(data, color=color, point_size=point_size, f_tooltip=f_tooltip))
Deprecated: use dot
def scatter(data, color=None, point_size=2, f_tooltip=None): """Deprecated: use dot """ import warnings warnings.warn("deprecated, use geoplotlib.dot", DeprecationWarning) dot(data, color, point_size, f_tooltip)
Create a 2D histogram :param data: data access object :param cmap: colormap name :param alpha: color alpha :param colorscale: scaling [lin, log, sqrt] :param binsize: size of the hist bins :param show_tooltip: if True, will show the value of bins on mouseover :param scalemin: min value for displaying a bin :param scalemax: max value for a bin :param f_group: function to apply to samples in the same bin. Default is to count :param show_colorbar: show colorbar
def hist(data, cmap='hot', alpha=220, colorscale='sqrt', binsize=16, show_tooltip=False, scalemin=0, scalemax=None, f_group=None, show_colorbar=True): """Create a 2D histogram :param data: data access object :param cmap: colormap name :param alpha: color alpha :param colorscale: scaling [lin, log, sqrt] :param binsize: size of the hist bins :param show_tooltip: if True, will show the value of bins on mouseover :param scalemin: min value for displaying a bin :param scalemax: max value for a bin :param f_group: function to apply to samples in the same bin. Default is to count :param show_colorbar: show colorbar """ from geoplotlib.layers import HistogramLayer _global_config.layers.append(HistogramLayer(data, cmap=cmap, alpha=alpha, colorscale=colorscale, binsize=binsize, show_tooltip=show_tooltip, scalemin=scalemin, scalemax=scalemax, f_group=f_group, show_colorbar=show_colorbar))
Create a graph drawing a line between each pair of (src_lat, src_lon) and (dest_lat, dest_lon) :param data: data access object :param src_lat: field name of source latitude :param src_lon: field name of source longitude :param dest_lat: field name of destination latitude :param dest_lon: field name of destination longitude :param linewidth: line width :param alpha: color alpha :param color: color or colormap
def graph(data, src_lat, src_lon, dest_lat, dest_lon, linewidth=1, alpha=220, color='hot'): """Create a graph drawing a line between each pair of (src_lat, src_lon) and (dest_lat, dest_lon) :param data: data access object :param src_lat: field name of source latitude :param src_lon: field name of source longitude :param dest_lat: field name of destination latitude :param dest_lon: field name of destination longitude :param linewidth: line width :param alpha: color alpha :param color: color or colormap """ from geoplotlib.layers import GraphLayer _global_config.layers.append(GraphLayer(data, src_lat, src_lon, dest_lat, dest_lon, linewidth, alpha, color))
Load and draws shapefiles :param fname: full path to the shapefile :param f_tooltip: function to generate a tooltip on mouseover :param color: color :param linewidth: line width :param shape_type: either full or bbox
def shapefiles(fname, f_tooltip=None, color=None, linewidth=3, shape_type='full'): """ Load and draws shapefiles :param fname: full path to the shapefile :param f_tooltip: function to generate a tooltip on mouseover :param color: color :param linewidth: line width :param shape_type: either full or bbox """ from geoplotlib.layers import ShapefileLayer _global_config.layers.append(ShapefileLayer(fname, f_tooltip, color, linewidth, shape_type))
Draw the voronoi tesselation of the points :param data: data access object :param line_color: line color :param line_width: line width :param f_tooltip: function to generate a tooltip on mouseover :param cmap: color map :param max_area: scaling constant to determine the color of the voronoi areas :param alpha: color alpha
def voronoi(data, line_color=None, line_width=2, f_tooltip=None, cmap=None, max_area=1e4, alpha=220): """ Draw the voronoi tesselation of the points :param data: data access object :param line_color: line color :param line_width: line width :param f_tooltip: function to generate a tooltip on mouseover :param cmap: color map :param max_area: scaling constant to determine the color of the voronoi areas :param alpha: color alpha """ from geoplotlib.layers import VoronoiLayer _global_config.layers.append(VoronoiLayer(data, line_color, line_width, f_tooltip, cmap, max_area, alpha))
Draw a delaunay triangulation of the points :param data: data access object :param line_color: line color :param line_width: line width :param cmap: color map :param max_lenght: scaling constant for coloring the edges
def delaunay(data, line_color=None, line_width=2, cmap=None, max_lenght=100): """ Draw a delaunay triangulation of the points :param data: data access object :param line_color: line color :param line_width: line width :param cmap: color map :param max_lenght: scaling constant for coloring the edges """ from geoplotlib.layers import DelaunayLayer _global_config.layers.append(DelaunayLayer(data, line_color, line_width, cmap, max_lenght))
Convex hull for a set of points :param data: points :param col: color :param fill: whether to fill the convexhull polygon or not :param point_size: size of the points on the convexhull. Points are not rendered if None
def convexhull(data, col, fill=True, point_size=4): """ Convex hull for a set of points :param data: points :param col: color :param fill: whether to fill the convexhull polygon or not :param point_size: size of the points on the convexhull. Points are not rendered if None """ from geoplotlib.layers import ConvexHullLayer _global_config.layers.append(ConvexHullLayer(data, col, fill, point_size))
Kernel density estimation visualization :param data: data access object :param bw: kernel bandwidth (in screen coordinates) :param cmap: colormap :param method: if kde use KDEMultivariate from statsmodel, which provides a more accurate but much slower estimation. If hist, estimates density applying gaussian smoothing on a 2D histogram, which is much faster but less accurate :param scaling: colorscale, lin log or sqrt :param alpha: color alpha :param cut_below: densities below cut_below are not drawn :param clip_above: defines the max value for the colorscale :param binsize: size of the bins for hist estimator :param cmap_levels: discretize colors into cmap_levels levels :param show_colorbar: show colorbar
def kde(data, bw, cmap='hot', method='hist', scaling='sqrt', alpha=220, cut_below=None, clip_above=None, binsize=1, cmap_levels=10, show_colorbar=False): """ Kernel density estimation visualization :param data: data access object :param bw: kernel bandwidth (in screen coordinates) :param cmap: colormap :param method: if kde use KDEMultivariate from statsmodel, which provides a more accurate but much slower estimation. If hist, estimates density applying gaussian smoothing on a 2D histogram, which is much faster but less accurate :param scaling: colorscale, lin log or sqrt :param alpha: color alpha :param cut_below: densities below cut_below are not drawn :param clip_above: defines the max value for the colorscale :param binsize: size of the bins for hist estimator :param cmap_levels: discretize colors into cmap_levels levels :param show_colorbar: show colorbar """ from geoplotlib.layers import KDELayer _global_config.layers.append(KDELayer(data, bw, cmap, method, scaling, alpha, cut_below, clip_above, binsize, cmap_levels, show_colorbar))
Draw markers :param data: data access object :param marker: full filename of the marker image :param f_tooltip: function to generate a tooltip on mouseover :param marker_preferred_size: size in pixel for the marker images
def markers(data, marker, f_tooltip=None, marker_preferred_size=32): """ Draw markers :param data: data access object :param marker: full filename of the marker image :param f_tooltip: function to generate a tooltip on mouseover :param marker_preferred_size: size in pixel for the marker images """ from geoplotlib.layers import MarkersLayer _global_config.layers.append(MarkersLayer(data, marker, f_tooltip, marker_preferred_size))
Draw features described in geojson format (http://geojson.org/) :param filename: filename of the geojson file :param color: color for the shapes. If callable, it will be invoked for each feature, passing the properties element :param linewidth: line width :param fill: if fill=True the feature polygon is filled, otherwise just the border is rendered :param f_tooltip: function to generate a tooltip on mouseover. It will be invoked for each feature, passing the properties element
def geojson(filename, color='b', linewidth=1, fill=False, f_tooltip=None): """ Draw features described in geojson format (http://geojson.org/) :param filename: filename of the geojson file :param color: color for the shapes. If callable, it will be invoked for each feature, passing the properties element :param linewidth: line width :param fill: if fill=True the feature polygon is filled, otherwise just the border is rendered :param f_tooltip: function to generate a tooltip on mouseover. It will be invoked for each feature, passing the properties element """ from geoplotlib.layers import GeoJSONLayer _global_config.layers.append(GeoJSONLayer(filename, color=color, linewidth=linewidth, fill=fill, f_tooltip=f_tooltip))
Draw a text label for each sample :param data: data access object :param label_column: column in the data access object where the labels text is stored :param color: color :param font_name: font name :param font_size: font size :param anchor_x: anchor x :param anchor_y: anchor y
def labels(data, label_column, color=None, font_name=FONT_NAME, font_size=14, anchor_x='left', anchor_y='top'): """ Draw a text label for each sample :param data: data access object :param label_column: column in the data access object where the labels text is stored :param color: color :param font_name: font name :param font_size: font size :param anchor_x: anchor x :param anchor_y: anchor y """ from geoplotlib.layers import LabelsLayer _global_config.layers.append(LabelsLayer(data, label_column, color, font_name, font_size, anchor_x, anchor_y))
Values on a uniform grid :param lon_edges: longitude edges :param lat_edges: latitude edges :param values: matrix representing values on the grid :param cmap: colormap name :param alpha: color alpha :param vmin: minimum value for the colormap :param vmax: maximum value for the colormap :param levels: number of levels for the colormap :param colormap_scale: colormap scale :param show_colorbar: show the colorbar in the UI
def grid(lon_edges, lat_edges, values, cmap, alpha=255, vmin=None, vmax=None, levels=10, colormap_scale='lin', show_colorbar=True): """ Values on a uniform grid :param lon_edges: longitude edges :param lat_edges: latitude edges :param values: matrix representing values on the grid :param cmap: colormap name :param alpha: color alpha :param vmin: minimum value for the colormap :param vmax: maximum value for the colormap :param levels: number of levels for the colormap :param colormap_scale: colormap scale :param show_colorbar: show the colorbar in the UI """ from geoplotlib.layers import GridLayer _global_config.layers.append( GridLayer(lon_edges, lat_edges, values, cmap, alpha, vmin, vmax, levels, colormap_scale, show_colorbar))
Alpha color of the map tiles :param alpha: int between 0 and 255. 0 is completely dark, 255 is full brightness
def set_map_alpha(alpha): """ Alpha color of the map tiles :param alpha: int between 0 and 255. 0 is completely dark, 255 is full brightness """ if alpha < 0 or alpha > 255: raise Exception('invalid alpha ' + str(alpha)) _global_config.map_alpha = alpha
Distance between geodesic coordinates http://www.movable-type.co.uk/scripts/latlong.html :param lon1: point 1 latitude :param lat1: point 1 longitude :param lon2: point 1 latitude :param lat2: point 2 longitude :return: distance in meters between points 1 and 2
def haversine(lon1, lat1, lon2, lat2): """ Distance between geodesic coordinates http://www.movable-type.co.uk/scripts/latlong.html :param lon1: point 1 latitude :param lat1: point 1 longitude :param lon2: point 1 latitude :param lat2: point 2 longitude :return: distance in meters between points 1 and 2 """ lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) m = 6367000 * c return m
Read a csv file into a DataAccessObject :param fname: filename
def read_csv(fname): """ Read a csv file into a DataAccessObject :param fname: filename """ values = defaultdict(list) with open(fname) as f: reader = csv.DictReader(f) for row in reader: for (k,v) in row.items(): values[k].append(v) npvalues = {k: np.array(values[k]) for k in values.keys()} for k in npvalues.keys(): for datatype in [np.int, np.float]: try: npvalues[k][:1].astype(datatype) npvalues[k] = npvalues[k].astype(datatype) break except: pass dao = DataAccessObject(npvalues) return dao
Rename fields :param mapping: a dict in the format {'oldkey1': 'newkey1', ...}
def rename(self, mapping): """ Rename fields :param mapping: a dict in the format {'oldkey1': 'newkey1', ...} """ for old_key, new_key in mapping: self.dict[new_key] = self.dict[old_key] del self.dict[old_key]
:param mask: boolean mask :return: a DataAccessObject with a subset of rows matching mask
def where(self, mask): """ :param mask: boolean mask :return: a DataAccessObject with a subset of rows matching mask """ assert len(mask) == len(self) return DataAccessObject({k: self.dict[k][mask] for k in self.dict})
Return a DataAccessObject containing the first n rows :param n: number of rows :return: DataAccessObject
def head(self, n): """ Return a DataAccessObject containing the first n rows :param n: number of rows :return: DataAccessObject """ return DataAccessObject({k: self.dict[k][:n] for k in self.dict})
Compute the BoundingBox from a set of latitudes and longitudes :param lons: longitudes :param lats: latitudes :return: BoundingBox
def from_points(lons, lats): """ Compute the BoundingBox from a set of latitudes and longitudes :param lons: longitudes :param lats: latitudes :return: BoundingBox """ north, west = max(lats), min(lons) south, east = min(lats), max(lons) return BoundingBox(north=north, west=west, south=south, east=east)
Compute a BoundingBox enclosing all specified bboxes :param bboxes: a list of BoundingBoxes :return: BoundingBox
def from_bboxes(bboxes): """ Compute a BoundingBox enclosing all specified bboxes :param bboxes: a list of BoundingBoxes :return: BoundingBox """ north = max([b.north for b in bboxes]) south = min([b.south for b in bboxes]) west = min([b.west for b in bboxes]) east = max([b.east for b in bboxes]) return BoundingBox(north=north, west=west, south=south, east=east)
return a dict of colors corresponding to the unique values :param values: values to be mapped :param cmap_name: colormap name :param alpha: color alpha :return: dict of colors corresponding to the unique values
def create_set_cmap(values, cmap_name, alpha=255): """ return a dict of colors corresponding to the unique values :param values: values to be mapped :param cmap_name: colormap name :param alpha: color alpha :return: dict of colors corresponding to the unique values """ unique_values = list(set(values)) shuffle(unique_values) from pylab import get_cmap cmap = get_cmap(cmap_name) d = {} for i in range(len(unique_values)): d[unique_values[i]] = _convert_color_format(cmap(1.*i/len(unique_values)), alpha) return d
Return a dict of colors for the unique values. Colors are adapted from Harrower, Mark, and Cynthia A. Brewer. "ColorBrewer. org: an online tool for selecting colour schemes for maps." The Cartographic Journal 40.1 (2003): 27-37. :param values: values :param alpha: color alphs :return: dict of colors for the unique values.
def colorbrewer(values, alpha=255): """ Return a dict of colors for the unique values. Colors are adapted from Harrower, Mark, and Cynthia A. Brewer. "ColorBrewer. org: an online tool for selecting colour schemes for maps." The Cartographic Journal 40.1 (2003): 27-37. :param values: values :param alpha: color alphs :return: dict of colors for the unique values. """ basecolors = [ [31, 120, 180], [178, 223, 138], [51, 160, 44], [251, 154, 153], [227, 26, 28], [253, 191, 111], [255, 127, 0], [202, 178, 214], [106, 61, 154], [255, 255, 153], [177, 89, 40] ] unique_values = list(set(values)) return {k: basecolors[i % len(basecolors)] + [alpha] for i, k in enumerate(unique_values)}
convert continuous values into colors using matplotlib colorscales :param value: value to be converted :param maxvalue: max value in the colorscale :param scale: lin, log, sqrt :param minvalue: minimum of the input values in linear scale (default is 0) :return: the color corresponding to the value
def to_color(self, value, maxvalue, scale, minvalue=0.0): """ convert continuous values into colors using matplotlib colorscales :param value: value to be converted :param maxvalue: max value in the colorscale :param scale: lin, log, sqrt :param minvalue: minimum of the input values in linear scale (default is 0) :return: the color corresponding to the value """ if scale == 'lin': if minvalue >= maxvalue: raise Exception('minvalue must be less than maxvalue') else: value = 1.*(value-minvalue) / (maxvalue-minvalue) elif scale == 'log': if value < 1 or maxvalue <= 1: raise Exception('value and maxvalue must be >= 1') else: value = math.log(value) / math.log(maxvalue) elif scale == 'sqrt': if value < 0 or maxvalue <= 0: raise Exception('value and maxvalue must be greater than 0') else: value = math.sqrt(value) / math.sqrt(maxvalue) else: raise Exception('scale must be "lin", "log", or "sqrt"') if value < 0: value = 0 elif value > 1: value = 1 value = int(1.*self.levels*value)*1./(self.levels-1) if value not in self.mapping: self.mapping[value] = _convert_color_format(self.cmap(value), self.alpha) return self.mapping[value]
catmullrom spline http://www.mvps.org/directx/articles/catmull/
def __generate_spline(self, x, y, closed=False, steps=20): """ catmullrom spline http://www.mvps.org/directx/articles/catmull/ """ if closed: x = x.tolist() x.insert(0, x[-1]) x.append(x[1]) x.append(x[2]) y = y.tolist() y.insert(0, y[-1]) y.append(y[1]) y.append(y[2]) points = np.vstack((x,y)).T curve = [] if not closed: curve.append(points[0]) for j in range(1, len(points)-2): for s in range(steps): t = 1. * s / steps p0, p1, p2, p3 = points[j-1], points[j], points[j+1], points[j+2] pnew = 0.5 *((2 * p1) + (-p0 + p2) * t + (2*p0 - 5*p1 + 4*p2 - p3) * t**2 + (-p0 + 3*p1- 3*p2 + p3) * t**3) curve.append(pnew) if not closed: curve.append(points[-1]) curve = np.array(curve) return curve[:, 0], curve[:, 1]
Fits the projector to a BoundingBox :param bbox: BoundingBox :param max_zoom: max zoom allowed :param force_zoom: force this specific zoom value even if the whole bbox does not completely fit
def fit(self, bbox, max_zoom=MAX_ZOOM, force_zoom=None): """ Fits the projector to a BoundingBox :param bbox: BoundingBox :param max_zoom: max zoom allowed :param force_zoom: force this specific zoom value even if the whole bbox does not completely fit """ BUFFER_FACTOR = 1.1 if force_zoom is not None: self.zoom = force_zoom else: for zoom in range(max_zoom, MIN_ZOOM-1, -1): self.zoom = zoom left, top = self.lonlat_to_screen([bbox.west], [bbox.north]) right, bottom = self.lonlat_to_screen([bbox.east], [bbox.south]) if (top - bottom < SCREEN_H*BUFFER_FACTOR) and (right - left < SCREEN_W*BUFFER_FACTOR): break west_tile, north_tile = self.deg2num(bbox.north, bbox.west, self.zoom) east_tile, south_tile = self.deg2num(bbox.south, bbox.east, self.zoom) self.xtile = west_tile - self.tiles_horizontally/2. + (east_tile - west_tile)/2 self.ytile = north_tile - self.tiles_vertically/2. + (south_tile - north_tile)/2 self.calculate_viewport_size()
Projects geodesic coordinates to screen :param lon: longitude :param lat: latitude :return: x,y screen coordinates
def lonlat_to_screen(self, lon, lat): """ Projects geodesic coordinates to screen :param lon: longitude :param lat: latitude :return: x,y screen coordinates """ if type(lon) == list: lon = np.array(lon) if type(lat) == list: lat = np.array(lat) lat_rad = np.radians(lat) n = 2.0 ** self.zoom xtile = (lon + 180.0) / 360.0 * n ytile = (1.0 - np.log(np.tan(lat_rad) + (1 / np.cos(lat_rad))) / math.pi) / 2.0 * n x = (xtile * TILE_SIZE).astype(int) y = (SCREEN_H - ytile * TILE_SIZE).astype(int) return x, y
Return the latitude and longitude corresponding to a screen point :param x: screen x :param y: screen y :return: latitude and longitude at x,y
def screen_to_latlon(self, x, y): """ Return the latitude and longitude corresponding to a screen point :param x: screen x :param y: screen y :return: latitude and longitude at x,y """ xtile = 1. * x / TILE_SIZE + self.xtile ytile = 1. * y / TILE_SIZE + self.ytile return self.num2deg(xtile, ytile, self.zoom)
Get possible completions for modulename for pydoc. Returns a list of possible values to be passed to pydoc.
def get_pydoc_completions(modulename): """Get possible completions for modulename for pydoc. Returns a list of possible values to be passed to pydoc. """ modulename = compat.ensure_not_unicode(modulename) modulename = modulename.rstrip(".") if modulename == "": return sorted(get_modules()) candidates = get_completions(modulename) if candidates: return sorted(candidates) needle = modulename if "." in needle: modulename, part = needle.rsplit(".", 1) candidates = get_completions(modulename) else: candidates = get_modules() return sorted(candidate for candidate in candidates if candidate.startswith(needle))
Return a list of modules and packages under modulename. If modulename is not given, return a list of all top level modules and packages.
def get_modules(modulename=None): """Return a list of modules and packages under modulename. If modulename is not given, return a list of all top level modules and packages. """ modulename = compat.ensure_not_unicode(modulename) if not modulename: try: return ([modname for (importer, modname, ispkg) in iter_modules() if not modname.startswith("_")] + list(sys.builtin_module_names)) except OSError: # Bug in Python 2.6, see #275 return list(sys.builtin_module_names) try: module = safeimport(modulename) except ErrorDuringImport: return [] if module is None: return [] if hasattr(module, "__path__"): return [modname for (importer, modname, ispkg) in iter_modules(module.__path__) if not modname.startswith("_")] return []
Read a single line and decode it as JSON. Can raise an EOFError() when the input source was closed.
def read_json(self): """Read a single line and decode it as JSON. Can raise an EOFError() when the input source was closed. """ line = self.stdin.readline() if line == '': raise EOFError() return json.loads(line)
Write an JSON object on a single line. The keyword arguments are interpreted as a single JSON object. It's not possible with this method to write non-objects.
def write_json(self, **kwargs): """Write an JSON object on a single line. The keyword arguments are interpreted as a single JSON object. It's not possible with this method to write non-objects. """ self.stdout.write(json.dumps(kwargs) + "\n") self.stdout.flush()
Handle a single JSON-RPC request. Read a request, call the appropriate handler method, and return the encoded result. Errors in the handler method are caught and encoded as error objects. Errors in the decoding phase are not caught, as we can not respond with an error response to them.
def handle_request(self): """Handle a single JSON-RPC request. Read a request, call the appropriate handler method, and return the encoded result. Errors in the handler method are caught and encoded as error objects. Errors in the decoding phase are not caught, as we can not respond with an error response to them. """ request = self.read_json() if 'method' not in request: raise ValueError("Received a bad request: {0}" .format(request)) method_name = request['method'] request_id = request.get('id', None) params = request.get('params') or [] try: method = getattr(self, "rpc_" + method_name, None) if method is not None: result = method(*params) else: result = self.handle(method_name, params) if request_id is not None: self.write_json(result=result, id=request_id) except Fault as fault: error = {"message": fault.message, "code": fault.code} if fault.data is not None: error["data"] = fault.data self.write_json(error=error, id=request_id) except Exception as e: error = {"message": str(e), "code": 500, "data": {"traceback": traceback.format_exc()}} self.write_json(error=error, id=request_id)
Formats Python code to conform to the PEP 8 style guide.
def fix_code(code, directory): """Formats Python code to conform to the PEP 8 style guide. """ if not autopep8: raise Fault('autopep8 not installed, cannot fix code.', code=400) old_dir = os.getcwd() try: os.chdir(directory) return autopep8.fix_code(code, apply_config=True) finally: os.chdir(old_dir)
Translate fileobj into file contents. fileobj is either a string or a dict. If it's a string, that's the file contents. If it's a string, then the filename key contains the name of the file whose contents we are to use. If the dict contains a true value for the key delete_after_use, the file should be deleted once read.
def get_source(fileobj): """Translate fileobj into file contents. fileobj is either a string or a dict. If it's a string, that's the file contents. If it's a string, then the filename key contains the name of the file whose contents we are to use. If the dict contains a true value for the key delete_after_use, the file should be deleted once read. """ if not isinstance(fileobj, dict): return fileobj else: try: with io.open(fileobj["filename"], encoding="utf-8", errors="ignore") as f: return f.read() finally: if fileobj.get('delete_after_use'): try: os.remove(fileobj["filename"]) except: # pragma: no cover pass
Call the backend method with args. If there is currently no backend, return default.
def _call_backend(self, method, default, *args, **kwargs): """Call the backend method with args. If there is currently no backend, return default.""" meth = getattr(self.backend, method, None) if meth is None: return default else: return meth(*args, **kwargs)
Get the calltip for the function at the offset.
def rpc_get_calltip(self, filename, source, offset): """Get the calltip for the function at the offset. """ return self._call_backend("rpc_get_calltip", None, filename, get_source(source), offset)
Get a oneline docstring for the symbol at the offset.
def rpc_get_oneline_docstring(self, filename, source, offset): """Get a oneline docstring for the symbol at the offset. """ return self._call_backend("rpc_get_oneline_docstring", None, filename, get_source(source), offset)
Get a list of completion candidates for the symbol at offset.
def rpc_get_completions(self, filename, source, offset): """Get a list of completion candidates for the symbol at offset. """ results = self._call_backend("rpc_get_completions", [], filename, get_source(source), offset) # Uniquify by name results = list(dict((res['name'], res) for res in results) .values()) results.sort(key=lambda cand: _pysymbol_key(cand["name"])) return results
Get the location of the definition for the symbol at the offset.
def rpc_get_definition(self, filename, source, offset): """Get the location of the definition for the symbol at the offset. """ return self._call_backend("rpc_get_definition", None, filename, get_source(source), offset)
Get the location of the assignment for the symbol at the offset.
def rpc_get_assignment(self, filename, source, offset): """Get the location of the assignment for the symbol at the offset. """ return self._call_backend("rpc_get_assignment", None, filename, get_source(source), offset)
Get the docstring for the symbol at the offset.
def rpc_get_docstring(self, filename, source, offset): """Get the docstring for the symbol at the offset. """ return self._call_backend("rpc_get_docstring", None, filename, get_source(source), offset)
Get the Pydoc documentation for the given symbol. Uses pydoc and can return a string with backspace characters for bold highlighting.
def rpc_get_pydoc_documentation(self, symbol): """Get the Pydoc documentation for the given symbol. Uses pydoc and can return a string with backspace characters for bold highlighting. """ try: docstring = pydoc.render_doc(str(symbol), "Elpy Pydoc Documentation for %s", False) except (ImportError, pydoc.ErrorDuringImport): return None else: if isinstance(docstring, bytes): docstring = docstring.decode("utf-8", "replace") return docstring
Return a list of possible refactoring options. This list will be filtered depending on whether it's applicable at the point START and possibly the region between START and END.
def rpc_get_refactor_options(self, filename, start, end=None): """Return a list of possible refactoring options. This list will be filtered depending on whether it's applicable at the point START and possibly the region between START and END. """ try: from elpy import refactor except: raise ImportError("Rope not installed, refactorings unavailable") ref = refactor.Refactor(self.project_root, filename) return ref.get_refactor_options(start, end)
Return a list of changes from the refactoring action. A change is a dictionary describing the change. See elpy.refactor.translate_changes for a description.
def rpc_refactor(self, filename, method, args): """Return a list of changes from the refactoring action. A change is a dictionary describing the change. See elpy.refactor.translate_changes for a description. """ try: from elpy import refactor except: raise ImportError("Rope not installed, refactorings unavailable") if args is None: args = () ref = refactor.Refactor(self.project_root, filename) return ref.get_changes(method, *args)
Get all possible names
def rpc_get_names(self, filename, source, offset): """Get all possible names """ source = get_source(source) if hasattr(self.backend, "rpc_get_names"): return self.backend.rpc_get_names(filename, source, offset) else: raise Fault("get_names not implemented by current backend", code=400)
Formats Python code to conform to the PEP 8 style guide.
def rpc_fix_code(self, source, directory): """Formats Python code to conform to the PEP 8 style guide. """ source = get_source(source) return fix_code(source, directory)
Formats Python code to conform to the PEP 8 style guide.
def rpc_fix_code_with_yapf(self, source, directory): """Formats Python code to conform to the PEP 8 style guide. """ source = get_source(source) return fix_code_with_yapf(source, directory)
Formats Python code to conform to the PEP 8 style guide.
def rpc_fix_code_with_black(self, source, directory): """Formats Python code to conform to the PEP 8 style guide. """ source = get_source(source) return fix_code_with_black(source, directory)
Return a tuple of line and column for offset pos in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why.
def pos_to_linecol(text, pos): """Return a tuple of line and column for offset pos in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why. """ line_start = text.rfind("\n", 0, pos) + 1 line = text.count("\n", 0, line_start) + 1 col = pos - line_start return line, col
Return the offset of this line and column in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why.
def linecol_to_pos(text, line, col): """Return the offset of this line and column in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why. """ nth_newline_offset = 0 for i in range(line - 1): new_offset = text.find("\n", nth_newline_offset) if new_offset < 0: raise ValueError("Text does not have {0} lines." .format(line)) nth_newline_offset = new_offset + 1 offset = nth_newline_offset + col if offset > len(text): raise ValueError("Line {0} column {1} is not within the text" .format(line, col)) return offset
Return a oneline docstring for the symbol at offset
def rpc_get_oneline_docstring(self, filename, source, offset): """Return a oneline docstring for the symbol at offset""" line, column = pos_to_linecol(source, offset) definitions = run_with_debug(jedi, 'goto_definitions', source=source, line=line, column=column, path=filename, encoding='utf-8') assignments = run_with_debug(jedi, 'goto_assignments', source=source, line=line, column=column, path=filename, encoding='utf-8') if definitions: definition = definitions[0] else: definition = None if assignments: assignment = assignments[0] else: assignment = None if definition: # Get name if definition.type in ['function', 'class']: raw_name = definition.name name = '{}()'.format(raw_name) doc = definition.docstring().split('\n') elif definition.type in ['module']: raw_name = definition.name name = '{} {}'.format(raw_name, definition.type) doc = definition.docstring().split('\n') elif (definition.type in ['instance'] and hasattr(assignment, "name")): raw_name = assignment.name name = raw_name doc = assignment.docstring().split('\n') else: return None # Keep only the first paragraph that is not a function declaration lines = [] call = "{}(".format(raw_name) # last line doc.append('') for i in range(len(doc)): if doc[i] == '' and len(lines) != 0: paragraph = " ".join(lines) lines = [] if call != paragraph[0:len(call)]: break paragraph = "" continue lines.append(doc[i]) # Keep only the first sentence onelinedoc = paragraph.split('. ', 1) if len(onelinedoc) == 2: onelinedoc = onelinedoc[0] + '.' else: onelinedoc = onelinedoc[0] if onelinedoc == '': onelinedoc = "No documentation" return {"name": name, "doc": onelinedoc} return None
Return the uses of the symbol at offset. Returns a list of occurrences of the symbol, as dicts with the fields name, filename, and offset.
def rpc_get_usages(self, filename, source, offset): """Return the uses of the symbol at offset. Returns a list of occurrences of the symbol, as dicts with the fields name, filename, and offset. """ line, column = pos_to_linecol(source, offset) uses = run_with_debug(jedi, 'usages', source=source, line=line, column=column, path=filename, encoding='utf-8') if uses is None: return None result = [] for use in uses: if use.module_path == filename: offset = linecol_to_pos(source, use.line, use.column) elif use.module_path is not None: with open(use.module_path) as f: text = f.read() offset = linecol_to_pos(text, use.line, use.column) result.append({"name": use.name, "filename": use.module_path, "offset": offset}) return result
Return the list of possible names
def rpc_get_names(self, filename, source, offset): """Return the list of possible names""" names = jedi.api.names(source=source, path=filename, encoding='utf-8', all_scopes=True, definitions=True, references=True) result = [] for name in names: if name.module_path == filename: offset = linecol_to_pos(source, name.line, name.column) elif name.module_path is not None: with open(name.module_path) as f: text = f.read() offset = linecol_to_pos(text, name.line, name.column) result.append({"name": name.name, "filename": name.module_path, "offset": offset}) return result
Formats Python code to conform to the PEP 8 style guide.
def fix_code(code, directory): """Formats Python code to conform to the PEP 8 style guide. """ if not black: raise Fault("black not installed", code=400) try: if parse_version(black.__version__) < parse_version("19.0"): reformatted_source = black.format_file_contents( src_contents=code, line_length=black.DEFAULT_LINE_LENGTH, fast=False ) else: fm = black.FileMode() reformatted_source = black.format_file_contents( src_contents=code, fast=False, mode=fm ) return reformatted_source except black.NothingChanged: return code except Exception as e: raise Fault("Error during formatting: {}".format(e), code=400)
Decorator to set some options on a method.
def options(description, **kwargs): """Decorator to set some options on a method.""" def set_notes(function): function.refactor_notes = {'name': function.__name__, 'category': "Miscellaneous", 'description': description, 'doc': getattr(function, '__doc__', ''), 'args': []} function.refactor_notes.update(kwargs) return function return set_notes
Translate rope.base.change.Change instances to dictionaries. See Refactor.get_changes for an explanation of the resulting dictionary.
def translate_changes(initial_change): """Translate rope.base.change.Change instances to dictionaries. See Refactor.get_changes for an explanation of the resulting dictionary. """ agenda = [initial_change] result = [] while agenda: change = agenda.pop(0) if isinstance(change, rope_change.ChangeSet): agenda.extend(change.changes) elif isinstance(change, rope_change.ChangeContents): result.append({'action': 'change', 'file': change.resource.real_path, 'contents': change.new_contents, 'diff': change.get_description()}) elif isinstance(change, rope_change.CreateFile): result.append({'action': 'create', 'type': 'file', 'file': change.resource.real_path}) elif isinstance(change, rope_change.CreateFolder): result.append({'action': 'create', 'type': 'directory', 'path': change.resource.real_path}) elif isinstance(change, rope_change.MoveResource): result.append({'action': 'move', 'type': ('directory' if change.new_resource.is_folder() else 'file'), 'source': change.resource.real_path, 'destination': change.new_resource.real_path}) elif isinstance(change, rope_change.RemoveResource): if change.resource.is_folder(): result.append({'action': 'delete', 'type': 'directory', 'path': change.resource.real_path}) else: result.append({'action': 'delete', 'type': 'file', 'file': change.resource.real_path}) return result
Return a list of options for refactoring at the given position. If `end` is also given, refactoring on a region is assumed. Each option is a dictionary of key/value pairs. The value of the key 'name' is the one to be used for get_changes. The key 'args' contains a list of additional arguments required for get_changes.
def get_refactor_options(self, start, end=None): """Return a list of options for refactoring at the given position. If `end` is also given, refactoring on a region is assumed. Each option is a dictionary of key/value pairs. The value of the key 'name' is the one to be used for get_changes. The key 'args' contains a list of additional arguments required for get_changes. """ result = [] for symbol in dir(self): if not symbol.startswith("refactor_"): continue method = getattr(self, symbol) if not method.refactor_notes.get('available', True): continue category = method.refactor_notes['category'] if end is not None and category != 'Region': continue if end is None and category == 'Region': continue is_on_symbol = self._is_on_symbol(start) if not is_on_symbol and category in ('Symbol', 'Method'): continue requires_import = method.refactor_notes.get('only_on_imports', False) if requires_import and not self._is_on_import_statement(start): continue result.append(method.refactor_notes) return result
Does this offset point to an import statement?
def _is_on_import_statement(self, offset): "Does this offset point to an import statement?" data = self.resource.read() bol = data.rfind("\n", 0, offset) + 1 eol = data.find("\n", 0, bol) if eol == -1: eol = len(data) line = data[bol:eol] line = line.strip() if line.startswith("import ") or line.startswith("from "): return True else: return False
Is this offset on a symbol?
def _is_on_symbol(self, offset): "Is this offset on a symbol?" if not ROPE_AVAILABLE: return False data = self.resource.read() if offset >= len(data): return False if data[offset] != '_' and not data[offset].isalnum(): return False word = worder.get_name_at(self.resource, offset) if word: return True else: return False
Return a list of changes for the named refactoring action. Changes are dictionaries describing a single action to be taken for the refactoring to be successful. A change has an action and possibly a type. In the description below, the action is before the slash and the type after it. change: Change file contents - file: The path to the file to change - contents: The new contents for the file - Diff: A unified diff showing the changes introduced create/file: Create a new file - file: The file to create create/directory: Create a new directory - path: The directory to create move/file: Rename a file - source: The path to the source file - destination: The path to the destination file name move/directory: Rename a directory - source: The path to the source directory - destination: The path to the destination directory name delete/file: Delete a file - file: The file to delete delete/directory: Delete a directory - path: The directory to delete
def get_changes(self, name, *args): """Return a list of changes for the named refactoring action. Changes are dictionaries describing a single action to be taken for the refactoring to be successful. A change has an action and possibly a type. In the description below, the action is before the slash and the type after it. change: Change file contents - file: The path to the file to change - contents: The new contents for the file - Diff: A unified diff showing the changes introduced create/file: Create a new file - file: The file to create create/directory: Create a new directory - path: The directory to create move/file: Rename a file - source: The path to the source file - destination: The path to the destination file name move/directory: Rename a directory - source: The path to the source directory - destination: The path to the destination directory name delete/file: Delete a file - file: The file to delete delete/directory: Delete a directory - path: The directory to delete """ if not name.startswith("refactor_"): raise ValueError("Bad refactoring name {0}".format(name)) method = getattr(self, name) if not method.refactor_notes.get('available', True): raise RuntimeError("Method not available") return method(*args)
Converting imports of the form "from ..." to "import ...".
def refactor_froms_to_imports(self, offset): """Converting imports of the form "from ..." to "import ...".""" refactor = ImportOrganizer(self.project) changes = refactor.froms_to_imports(self.resource, offset) return translate_changes(changes)
Clean up and organize imports.
def refactor_organize_imports(self): """Clean up and organize imports.""" refactor = ImportOrganizer(self.project) changes = refactor.organize_imports(self.resource) return translate_changes(changes)
Convert the current module into a package.
def refactor_module_to_package(self): """Convert the current module into a package.""" refactor = ModuleToPackage(self.project, self.resource) return self._get_changes(refactor)
Rename the symbol at point.
def refactor_rename_at_point(self, offset, new_name, in_hierarchy, docs): """Rename the symbol at point.""" try: refactor = Rename(self.project, self.resource, offset) except RefactoringError as e: raise Fault(str(e), code=400) return self._get_changes(refactor, new_name, in_hierarchy=in_hierarchy, docs=docs)
Rename the current module.
def refactor_rename_current_module(self, new_name): """Rename the current module.""" refactor = Rename(self.project, self.resource, None) return self._get_changes(refactor, new_name)
Move the current module.
def refactor_move_module(self, new_name): """Move the current module.""" refactor = create_move(self.project, self.resource) resource = path_to_resource(self.project, new_name) return self._get_changes(refactor, resource)
Inline the function call at point.
def refactor_create_inline(self, offset, only_this): """Inline the function call at point.""" refactor = create_inline(self.project, self.resource, offset) if only_this: return self._get_changes(refactor, remove=False, only_current=True) else: return self._get_changes(refactor, remove=True, only_current=False)
Extract region as a method.
def refactor_extract_method(self, start, end, name, make_global): """Extract region as a method.""" refactor = ExtractMethod(self.project, self.resource, start, end) return self._get_changes( refactor, name, similar=True, global_=make_global )
Use the function at point wherever possible.
def refactor_use_function(self, offset): """Use the function at point wherever possible.""" try: refactor = UseFunction(self.project, self.resource, offset) except RefactoringError as e: raise Fault( 'Refactoring error: {}'.format(e), code=400 ) return self._get_changes(refactor)
Formats Python code to conform to the PEP 8 style guide.
def fix_code(code, directory): """Formats Python code to conform to the PEP 8 style guide. """ if not yapf_api: raise Fault('yapf not installed', code=400) style_config = file_resources.GetDefaultStyleForDir(directory or os.getcwd()) try: reformatted_source, _ = yapf_api.FormatCode(code, filename='<stdin>', style_config=style_config, verify=False) return reformatted_source except Exception as e: raise Fault("Error during formatting: {}".format(e), code=400)
Send single buffer `payload` and receive a single buffer. Args: payload(bytes): Data to send.
def _send_receive(self, payload): """ Send single buffer `payload` and receive a single buffer. Args: payload(bytes): Data to send. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.settimeout(self.connection_timeout) s.connect((self.address, self.port)) s.send(payload) data = s.recv(1024) s.close() return data
Generate the payload to send. Args: command(str): The type of command. This is one of the entries from payload_dict data(dict, optional): The data to be send. This is what will be passed via the 'dps' entry
def generate_payload(self, command, data=None): """ Generate the payload to send. Args: command(str): The type of command. This is one of the entries from payload_dict data(dict, optional): The data to be send. This is what will be passed via the 'dps' entry """ json_data = payload_dict[self.dev_type][command]['command'] if 'gwId' in json_data: json_data['gwId'] = self.id if 'devId' in json_data: json_data['devId'] = self.id if 'uid' in json_data: json_data['uid'] = self.id # still use id, no seperate uid if 't' in json_data: json_data['t'] = str(int(time.time())) if data is not None: json_data['dps'] = data # Create byte buffer from hex data json_payload = json.dumps(json_data) #print(json_payload) json_payload = json_payload.replace(' ', '') # if spaces are not removed device does not respond! json_payload = json_payload.encode('utf-8') log.debug('json_payload=%r', json_payload) if command == SET: # need to encrypt #print('json_payload %r' % json_payload) self.cipher = AESCipher(self.local_key) # expect to connect and then disconnect to set new json_payload = self.cipher.encrypt(json_payload) #print('crypted json_payload %r' % json_payload) preMd5String = b'data=' + json_payload + b'||lpv=' + PROTOCOL_VERSION_BYTES + b'||' + self.local_key #print('preMd5String %r' % preMd5String) m = md5() m.update(preMd5String) #print(repr(m.digest())) hexdigest = m.hexdigest() #print(hexdigest) #print(hexdigest[8:][:16]) json_payload = PROTOCOL_VERSION_BYTES + hexdigest[8:][:16].encode('latin1') + json_payload #print('data_to_send') #print(json_payload) #print('crypted json_payload (%d) %r' % (len(json_payload), json_payload)) #print('json_payload %r' % repr(json_payload)) #print('json_payload len %r' % len(json_payload)) #print(bin2hex(json_payload)) self.cipher = None # expect to connect and then disconnect to set new postfix_payload = hex2bin(bin2hex(json_payload) + payload_dict[self.dev_type]['suffix']) #print('postfix_payload %r' % postfix_payload) #print('postfix_payload %r' % len(postfix_payload)) #print('postfix_payload %x' % len(postfix_payload)) #print('postfix_payload %r' % hex(len(postfix_payload))) assert len(postfix_payload) <= 0xff postfix_payload_hex_len = '%x' % len(postfix_payload) # TODO this assumes a single byte 0-255 (0x00-0xff) buffer = hex2bin( payload_dict[self.dev_type]['prefix'] + payload_dict[self.dev_type][command]['hexByte'] + '000000' + postfix_payload_hex_len ) + postfix_payload #print('command', command) #print('prefix') #print(payload_dict[self.dev_type][command]['prefix']) #print(repr(buffer)) #print(bin2hex(buffer, pretty=True)) #print(bin2hex(buffer, pretty=False)) #print('full buffer(%d) %r' % (len(buffer), buffer)) return buffer
Set status of the device to 'on' or 'off'. Args: on(bool): True for 'on', False for 'off'. switch(int): The switch to set
def set_status(self, on, switch=1): """ Set status of the device to 'on' or 'off'. Args: on(bool): True for 'on', False for 'off'. switch(int): The switch to set """ # open device, send request, then close connection if isinstance(switch, int): switch = str(switch) # index and payload is a string payload = self.generate_payload(SET, {switch:on}) #print('payload %r' % payload) data = self._send_receive(payload) log.debug('set_status received data=%r', data) return data
Set a timer. Args: num_secs(int): Number of seconds
def set_timer(self, num_secs): """ Set a timer. Args: num_secs(int): Number of seconds """ # FIXME / TODO support schemas? Accept timer id number as parameter? # Dumb heuristic; Query status, pick last device id as that is probably the timer status = self.status() devices = status['dps'] devices_numbers = list(devices.keys()) devices_numbers.sort() dps_id = devices_numbers[-1] payload = self.generate_payload(SET, {dps_id:num_secs}) data = self._send_receive(payload) log.debug('set_timer received data=%r', data) return data
Convert an RGB value to the hex representation expected by tuya. Index '5' (DPS_INDEX_COLOUR) is assumed to be in the format: rrggbb0hhhssvv While r, g and b are just hexadecimal values of the corresponding Red, Green and Blue values, the h, s and v values (which are values between 0 and 1) are scaled to 360 (h) and 255 (s and v) respectively. Args: r(int): Value for the colour red as int from 0-255. g(int): Value for the colour green as int from 0-255. b(int): Value for the colour blue as int from 0-255.
def _rgb_to_hexvalue(r, g, b): """ Convert an RGB value to the hex representation expected by tuya. Index '5' (DPS_INDEX_COLOUR) is assumed to be in the format: rrggbb0hhhssvv While r, g and b are just hexadecimal values of the corresponding Red, Green and Blue values, the h, s and v values (which are values between 0 and 1) are scaled to 360 (h) and 255 (s and v) respectively. Args: r(int): Value for the colour red as int from 0-255. g(int): Value for the colour green as int from 0-255. b(int): Value for the colour blue as int from 0-255. """ rgb = [r,g,b] hsv = colorsys.rgb_to_hsv(rgb[0]/255, rgb[1]/255, rgb[2]/255) hexvalue = "" for value in rgb: temp = str(hex(int(value))).replace("0x","") if len(temp) == 1: temp = "0" + temp hexvalue = hexvalue + temp hsvarray = [int(hsv[0] * 360), int(hsv[1] * 255), int(hsv[2] * 255)] hexvalue_hsv = "" for value in hsvarray: temp = str(hex(int(value))).replace("0x","") if len(temp) == 1: temp = "0" + temp hexvalue_hsv = hexvalue_hsv + temp if len(hexvalue_hsv) == 7: hexvalue = hexvalue + "0" + hexvalue_hsv else: hexvalue = hexvalue + "00" + hexvalue_hsv return hexvalue
Converts the hexvalue used by tuya for colour representation into an RGB value. Args: hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
def _hexvalue_to_rgb(hexvalue): """ Converts the hexvalue used by tuya for colour representation into an RGB value. Args: hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue() """ r = int(hexvalue[0:2], 16) g = int(hexvalue[2:4], 16) b = int(hexvalue[4:6], 16) return (r, g, b)
Converts the hexvalue used by tuya for colour representation into an HSV value. Args: hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
def _hexvalue_to_hsv(hexvalue): """ Converts the hexvalue used by tuya for colour representation into an HSV value. Args: hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue() """ h = int(hexvalue[7:10], 16) / 360 s = int(hexvalue[10:12], 16) / 255 v = int(hexvalue[12:14], 16) / 255 return (h, s, v)
Set colour of an rgb bulb. Args: r(int): Value for the colour red as int from 0-255. g(int): Value for the colour green as int from 0-255. b(int): Value for the colour blue as int from 0-255.
def set_colour(self, r, g, b): """ Set colour of an rgb bulb. Args: r(int): Value for the colour red as int from 0-255. g(int): Value for the colour green as int from 0-255. b(int): Value for the colour blue as int from 0-255. """ if not 0 <= r <= 255: raise ValueError("The value for red needs to be between 0 and 255.") if not 0 <= g <= 255: raise ValueError("The value for green needs to be between 0 and 255.") if not 0 <= b <= 255: raise ValueError("The value for blue needs to be between 0 and 255.") #print(BulbDevice) hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b) payload = self.generate_payload(SET, { self.DPS_INDEX_MODE: self.DPS_MODE_COLOUR, self.DPS_INDEX_COLOUR: hexvalue}) data = self._send_receive(payload) return data
Set white coloured theme of an rgb bulb. Args: brightness(int): Value for the brightness (25-255). colourtemp(int): Value for the colour temperature (0-255).
def set_white(self, brightness, colourtemp): """ Set white coloured theme of an rgb bulb. Args: brightness(int): Value for the brightness (25-255). colourtemp(int): Value for the colour temperature (0-255). """ if not 25 <= brightness <= 255: raise ValueError("The brightness needs to be between 25 and 255.") if not 0 <= colourtemp <= 255: raise ValueError("The colour temperature needs to be between 0 and 255.") payload = self.generate_payload(SET, { self.DPS_INDEX_MODE: self.DPS_MODE_WHITE, self.DPS_INDEX_BRIGHTNESS: brightness, self.DPS_INDEX_COLOURTEMP: colourtemp}) data = self._send_receive(payload) return data
Set the brightness value of an rgb bulb. Args: brightness(int): Value for the brightness (25-255).
def set_brightness(self, brightness): """ Set the brightness value of an rgb bulb. Args: brightness(int): Value for the brightness (25-255). """ if not 25 <= brightness <= 255: raise ValueError("The brightness needs to be between 25 and 255.") payload = self.generate_payload(SET, {self.DPS_INDEX_BRIGHTNESS: brightness}) data = self._send_receive(payload) return data
Set the colour temperature of an rgb bulb. Args: colourtemp(int): Value for the colour temperature (0-255).
def set_colourtemp(self, colourtemp): """ Set the colour temperature of an rgb bulb. Args: colourtemp(int): Value for the colour temperature (0-255). """ if not 0 <= colourtemp <= 255: raise ValueError("The colour temperature needs to be between 0 and 255.") payload = self.generate_payload(SET, {self.DPS_INDEX_COLOURTEMP: colourtemp}) data = self._send_receive(payload) return data
Return colour as RGB value
def colour_rgb(self): """Return colour as RGB value""" hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR] return BulbDevice._hexvalue_to_rgb(hexvalue)
Return colour as HSV value
def colour_hsv(self): """Return colour as HSV value""" hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR] return BulbDevice._hexvalue_to_hsv(hexvalue)
Set the group mask that the Crazyflie belongs to :param group_mask: mask for which groups this CF belongs to
def set_group_mask(self, group_mask=ALL_GROUPS): """ Set the group mask that the Crazyflie belongs to :param group_mask: mask for which groups this CF belongs to """ self._send_packet(struct.pack('<BB', self.COMMAND_SET_GROUP_MASK, group_mask))
vertical takeoff from current x-y position to given height :param absolute_height_m: absolut (m) :param duration_s: time it should take until target height is reached (s) :param group_mask: mask for which CFs this should apply to
def takeoff(self, absolute_height_m, duration_s, group_mask=ALL_GROUPS): """ vertical takeoff from current x-y position to given height :param absolute_height_m: absolut (m) :param duration_s: time it should take until target height is reached (s) :param group_mask: mask for which CFs this should apply to """ self._send_packet(struct.pack('<BBff', self.COMMAND_TAKEOFF, group_mask, absolute_height_m, duration_s))
vertical land from current x-y position to given height :param absolute_height_m: absolut (m) :param duration_s: time it should take until target height is reached (s) :param group_mask: mask for which CFs this should apply to
def land(self, absolute_height_m, duration_s, group_mask=ALL_GROUPS): """ vertical land from current x-y position to given height :param absolute_height_m: absolut (m) :param duration_s: time it should take until target height is reached (s) :param group_mask: mask for which CFs this should apply to """ self._send_packet(struct.pack('<BBff', self.COMMAND_LAND, group_mask, absolute_height_m, duration_s))
stops the current trajectory (turns off the motors) :param group_mask: mask for which CFs this should apply to :return:
def stop(self, group_mask=ALL_GROUPS): """ stops the current trajectory (turns off the motors) :param group_mask: mask for which CFs this should apply to :return: """ self._send_packet(struct.pack('<BB', self.COMMAND_STOP, group_mask))
Go to an absolute or relative position :param x: x (m) :param y: y (m) :param z: z (m) :param yaw: yaw (radians) :param duration_s: time it should take to reach the position (s) :param relative: True if x, y, z is relative to the current position :param group_mask: mask for which CFs this should apply to
def go_to(self, x, y, z, yaw, duration_s, relative=False, group_mask=ALL_GROUPS): """ Go to an absolute or relative position :param x: x (m) :param y: y (m) :param z: z (m) :param yaw: yaw (radians) :param duration_s: time it should take to reach the position (s) :param relative: True if x, y, z is relative to the current position :param group_mask: mask for which CFs this should apply to """ self._send_packet(struct.pack('<BBBfffff', self.COMMAND_GO_TO, group_mask, relative, x, y, z, yaw, duration_s))
starts executing a specified trajectory :param trajectory_id: id of the trajectory (previously defined by define_trajectory) :param time_scale: time factor; 1.0 = original speed; >1.0: slower; <1.0: faster :param relative: set to True, if trajectory should be shifted to current setpoint :param reversed: set to True, if trajectory should be executed in reverse :param group_mask: mask for which CFs this should apply to :return:
def start_trajectory(self, trajectory_id, time_scale=1.0, relative=False, reversed=False, group_mask=ALL_GROUPS): """ starts executing a specified trajectory :param trajectory_id: id of the trajectory (previously defined by define_trajectory) :param time_scale: time factor; 1.0 = original speed; >1.0: slower; <1.0: faster :param relative: set to True, if trajectory should be shifted to current setpoint :param reversed: set to True, if trajectory should be executed in reverse :param group_mask: mask for which CFs this should apply to :return: """ self._send_packet(struct.pack('<BBBBBf', self.COMMAND_START_TRAJECTORY, group_mask, relative, reversed, trajectory_id, time_scale))
Define a trajectory that has previously been uploaded to memory. :param trajectory_id: The id of the trajectory :param offset: offset in uploaded memory :param n_pieces: Nr of pieces in the trajectory :return:
def define_trajectory(self, trajectory_id, offset, n_pieces): """ Define a trajectory that has previously been uploaded to memory. :param trajectory_id: The id of the trajectory :param offset: offset in uploaded memory :param n_pieces: Nr of pieces in the trajectory :return: """ self._send_packet(struct.pack('<BBBBIB', self.COMMAND_DEFINE_TRAJECTORY, trajectory_id, self.TRAJECTORY_LOCATION_MEM, self.TRAJECTORY_TYPE_POLY4D, offset, n_pieces))
Interactively choose one of the items.
def choose(items, title_text, question_text): """ Interactively choose one of the items. """ print(title_text) for i, item in enumerate(items, start=1): print('%d) %s' % (i, item)) print('%d) Abort' % (i + 1)) selected = input(question_text) try: index = int(selected) except ValueError: index = -1 if not (index - 1) in range(len(items)): print('Aborting.') return None return items[index - 1]
Scan for Crazyflie and return its URI.
def scan(): """ Scan for Crazyflie and return its URI. """ # Initiate the low level drivers cflib.crtp.init_drivers(enable_debug_driver=False) # Scan for Crazyflies print('Scanning interfaces for Crazyflies...') available = cflib.crtp.scan_interfaces() interfaces = [uri for uri, _ in available] if not interfaces: return None return choose(interfaces, 'Crazyflies found:', 'Select interface: ')