def process(data): positions = [pos for pos, vel in data] velocities = [vel for pos, vel in data] prev_width, prev_height = None, None left, top = 0, 0 best_positions = None while True: left, right = minmax(x for x, y in positions) top, bottom = minmax(y for x, y in positions) width, height = right - left, bottom - top if prev_width and width > prev_width and prev_height and height > prev_height: break else: prev_width, prev_height = width, height best_positions = positions.copy() for i, (dx, dy) in enumerate(velocities): x, y = positions[i] x += dx y += dy positions[i] = (x, y) c = Canvas() for x, y in best_positions: c.set(x - left, y - top) print(c.frame())
def __main__(stdscr, projection=False): angleX, angleY, angleZ = 0, 0, 0 c = Canvas() while 1: # Will hold transformed vertices. t = [] for v in vertices: # Rotate the point around X axis, then around Y axis, and finally around Z axis. p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ) if projection: # Transform the point from 3D to 2D p = p.project(50, 50, 50, 50) #Put the point in the list of transformed vertices t.append(p) for f in faces: for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y): c.set(x, y) for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y): c.set(x, y) for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y): c.set(x, y) for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y): c.set(x, y) f = c.frame(-40, -40, 80, 80) stdscr.addstr(0, 0, '{0}\n'.format(f)) stdscr.refresh() angleX += 2 angleY += 3 angleZ += 5 sleep(1.0 / 20) c.clear()
def draw_simple_map(stdscr): c = Canvas() v1 = Point(-20, 20) v2 = Point(20, 20) v3 = Point(-20, -20) v4 = Point(20, -20) lines = [ (v1, v2), (v1, v3), (v3, v4), (v4, v2), ] for start, end in lines: for x, y in line(start.x, start.y, end.x, end.y): c.set(x, y) df = c.frame(-40, -40, 80, 80) stdscr.addstr(1, 0, f"{df}") stdscr.refresh() sleep(10) c.clear()
def __main__(stdscr, projection=False): angleX, angleY, angleZ = 0, 0, 0 c = Canvas() while 1: # Will hold transformed vertices. t = [] for v in vertices: # Rotate the point around X axis, then around Y axis, and finally around Z axis. p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ) if projection: # Transform the point from 3D to 2D p = p.project(50, 50, 50, 50) #Put the point in the list of transformed vertices t.append(p) for f in faces: for x,y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y): c.set(x,y) for x,y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y): c.set(x,y) for x,y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y): c.set(x,y) for x,y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y): c.set(x,y) f = c.frame(-40, -40, 80, 80) stdscr.addstr(0, 0, '{0}\n'.format(f)) stdscr.refresh() angleX += 2 angleY += 3 angleZ += 5 sleep(1.0/20) c.clear()
def image2term(image, threshold=128, ratio=None, invert=False): if image.startswith('http://') or image.startswith('https://'): i = Image.open(StringIO(urllib2.urlopen(image).read())).convert('L') else: i = Image.open(open(image)).convert('L') w, h = i.size if ratio: w = int(w * ratio) h = int(h * ratio) i = i.resize((w, h), Image.ANTIALIAS) else: tw, th = getTerminalSize() tw *= 2 th *= 2 if tw < w: ratio = tw / float(w) w = tw h = int(h * ratio) i = i.resize((w, h), Image.ANTIALIAS) can = Canvas() x = y = 0 for pix in i.tobytes(): if invert: if ord(pix) > threshold: can.set(x, y) else: if ord(pix) < threshold: can.set(x, y) x += 1 if x >= w: y += 1 x = 0 return can.frame(0, 0)
def image2term(image, threshold=128, ratio=None): if image.startswith('http://') or image.startswith('https://'): i = Image.open(StringIO(urllib2.urlopen(image).read())).convert('L') else: i = Image.open(open(image)).convert('L') w, h = i.size if ratio: w = int(w * ratio) h = int(h * ratio) i = i.resize((w, h), Image.ANTIALIAS) else: tw, th = getTerminalSize() tw *= 2 th *= 2 if tw < w: ratio = tw / float(w) w = tw h = int(h * ratio) i = i.resize((w, h), Image.ANTIALIAS) can = Canvas() x = y = 0 for pix in i.tobytes(): if ord(pix) < threshold: can.set(x, y) x += 1 if x >= w: y += 1 x = 0 return can.frame()
def image2term(image, threshold=128, ratio=None, invert=False): """ Prints an image converted to drawille Args: image: filepath / URL of the image threshold: The color (0-255) threshold to convert a pixel to a drawille dot ratio: Ratio to scale the printed image (e.g. ratio=0.5 is 50%) invert: Inverts the threshold check """ if image.startswith('http://') or image.startswith('https://'): r = requests.get(image,stream=True) i = Image.open(r.raw).convert('L') else: f = open(image,'rb') #Open in binary mode i = Image.open(f).convert('L') image_width, image_height = i.size if ratio: image_width = int(image_width * ratio) image_height = int(image_height * ratio) i = i.resize((image_width, image_height), Image.ANTIALIAS) else: terminal_width = getTerminalSize()[0] * 2#Number of Columns terminal_height = getTerminalSize()[1] * 4 w_ratio = 1 h_ratio = 1 if terminal_width < image_width: w_ratio = terminal_width / float(image_width) if terminal_height < image_height: h_ratio = terminal_height / float(image_height) ratio = min([w_ratio,h_ratio]) image_width = int(image_width * ratio) image_height = int(image_height * ratio) i = i.resize((image_width, image_height), Image.ANTIALIAS) can = Canvas() x = y = 0 try: i_converted = i.tobytes() except AttributeError: i_converted = i.tostring() for pix in i_converted: if invert: if pix > threshold: can.set(x, y) else: if pix < threshold: can.set(x, y) x += 1 if x >= image_width: y += 1 x = 0 return can.frame(0, 0)
def update(im, delay=0.1): im = im.resize((CANVAS_W, CANVAS_H)) canvas = Canvas() any(canvas.set(i % CANVAS_W, i // CANVAS_W) for i, px in enumerate(im.tobytes()) if px) print(canvas.frame(0, 0, CANVAS_W, CANVAS_H), end='') time.sleep(delay)
def draw(self): """Draw the graph """ c = Canvas() for node in self.nodes.itervalues(): self.draw_node(c, node) for edge in self.edges: self.draw_edge(c, edge) print(c.frame())
def setup(): # set the size of the board to the size of the terminal at ther start width, height = os.popen('stty size', 'r').read().split() height, width = 50, 50 board = Canvas() frame = (0, 0, width, height) assert(frame[YSEC] == height) board.frame(*frame) draw_bounds(board, frame) # get some paddles lpaddle = Paddle('left', board, frame) rpaddle = Paddle('right', board, frame) ball = Ball(board, frame) # get some output! stdscr = curses.initscr() stdscr.refresh() return (lpaddle, rpaddle, ball), board, frame, stdscr
def complexset2drawille(complexset, n): can = Canvas() w, h = getTerminalSize() w *= 2 h *= 4 for row in range(h): for col in range(w): if complexset.plot(col, row, w, h, n) >= complexset.MAX_ITER: can.set(col, row) return can.frame()
def spawn(self): while(True): self.spawn_next() print(chr(27) + "[2J") _canvas = Canvas() for room in self.queue: draw(_canvas, room) print(_canvas.frame()) if self.total_amount_required == 0: # seal all doors for room in self.queue: for door in room.available_doors: room.doors.remove(door) print(chr(27) + "[2J") _canvas = Canvas() for room in self.queue: draw(_canvas, room) print(_canvas.frame()) break time.sleep(0.05)
def __main__(): args = argparser() out = args['output'] orig_img = image.load(args['image']).convert('RGB') if args['contrast'] != None: orig_img = ImageEnhance.Contrast(orig_img).enhance(args['contrast']) orig_img = resizer.resize(orig_img, 1, ANTI_FONT_DISTORTION) fit_ratio = resizer.fit_in_ratio(orig_img.size, term.size()) if args['ratio']: fit_ratio *= args['ratio'] img = resizer.resize(orig_img, fit_ratio, (1, 1)) lows, mids, highs = posterizer.thresholds(img) if args['color'] != None: lows = map(lambda val: bound_addition(val, args['color']), lows) mids = map(lambda val: bound_addition(val, args['color']), mids) highs = map(lambda val: bound_addition(val, args['color']), highs) colors = posterizer.posterize(img, mids, highs) # img.show() shapes = resizer.resize(orig_img, fit_ratio, (2, 4)) # shapes.show() shapes = shapes.convert('L') threshold = otsu.threshold(shapes.histogram()) # mask = shapes.point(lambda val: 255 if val <= threshold else 0).convert('1') # threshold = otsu.threshold(shapes.histogram(mask)) if args['shape'] != None: threshold = bound_addition(threshold, args['shape']) shapes = shapes.point(lambda val: 255 if val > threshold else 0).convert('1') # shapes.show() dots = Canvas() w, h = shapes.size for index, pixel in enumerate(list(shapes.getdata()), 0): if pixel: dots.set(index % w, index // w) # out.write(dots.frame(0,0,w,h)) # out.write('\n') w, h = colors.size for index, pixel in enumerate(list(colors.getdata()), 0): x = (index % w) * 2 y = (index // w) * 4 miniframe = unicode(dots.frame(x, y, x + 2, y + 4), 'utf-8') miniframe = miniframe if len(miniframe) else u'\u2800' out.write(color_print.rgb2esc(pixel, [0, 0, 0], lows, highs, miniframe)) if not (1 + index) % w: out.write('\n')
def main(stdscr): global frame_no, speed, fps, position, delta, score c = Canvas() bar_width = 16 bars = [Bar(bar_width)] stdscr.refresh() while True: frame_no += 1 for bar in bars: if check_collision(position, bar): return while not keys.empty(): if keys.get() == 113: return speed = 32.0 c.set(0,0) c.set(width, height) if frame_no % 50 == 0: bars.append(Bar(bar_width)) for x,y in bird: c.set(x,y+position) for bar_index, bar in enumerate(bars): if bar.x < 1: bars.pop(bar_index) score += 1 else: bars[bar_index].x -= 1 for x,y in bar.draw(): c.set(x,y) f = c.frame()+'\n' stdscr.addstr(0, 0, f) stdscr.addstr(height/4+1, 0, 'score: {0}'.format(score)) stdscr.refresh() c.clear() speed -= 2 position -= speed/10 if position < 0: position = 0 speed = 0.0 elif position > height-13: position = height-13 speed = 0.0 sleep(1.0/fps)
def main(stdscr): global frame_no, speed, position, score c = Canvas() bar_width = 16 bars = [Bar(bar_width)] stdscr.refresh() while True: frame_no += 1 for bar in bars: if check_collision(position, bar): return while not keys.empty(): if keys.get() == 113: return speed = 32.0 c.set(0,0) c.set(width, height) if frame_no % 50 == 0: bars.append(Bar(bar_width)) for x,y in bird: c.set(x,y+position) for bar_index, bar in enumerate(bars): if bar.x < 1: bars.pop(bar_index) score += 1 else: bars[bar_index].x -= 1 for x,y in bar.draw(): c.set(x,y) f = c.frame()+'\n' stdscr.addstr(0, 0, f) stdscr.addstr(height/4+1, 0, 'score: {0}'.format(score)) stdscr.refresh() c.clear() speed -= 2 position -= speed/10 if position < 0: position = 0 speed = 0.0 elif position > height-13: position = height-13 speed = 0.0 sleep(1.0/fps)
def __main__(stdscr, projection=False): angleX, angleY, angleZ = 0, 0, 0 canvas = Canvas() while 1: # Will hold transformed vertices. transformed_vertices = [] for vertex in vertices: # Rotate the point around X axis, then around Y axis, and finally around Z axis. point = vertex.rotateX(angleX).rotateY(angleY).rotateZ(angleZ) if projection: # Transform the point from 3D to 2D point = point.project(50, 50, 50, 50) #Put the point in the list of transformed vertices transformed_vertices.append(point) for face in faces: for x, y in line(transformed_vertices[face[0]].x, transformed_vertices[face[0]].y, transformed_vertices[face[1]].x, transformed_vertices[face[1]].y): canvas.set(x, y) for x, y in line(transformed_vertices[face[1]].x, transformed_vertices[face[1]].y, transformed_vertices[face[2]].x, transformed_vertices[face[2]].y): canvas.set(x, y) for x, y in line(transformed_vertices[face[2]].x, transformed_vertices[face[2]].y, transformed_vertices[face[3]].x, transformed_vertices[face[3]].y): canvas.set(x, y) for x, y in line(transformed_vertices[face[3]].x, transformed_vertices[face[3]].y, transformed_vertices[face[0]].x, transformed_vertices[face[0]].y): canvas.set(x, y) frame = canvas.frame(-40, -40, 80, 80) stdscr.addstr(0, 0, '{0}\n'.format(frame)) stdscr.refresh() angleX += 2 angleY += 3 angleZ += 5 sleep(1.0 / 20) canvas.clear()
def __main__(stdscr): i = 0 c = Canvas() height = 40 while True: for x,y in line(0, height, 180, int(math.sin(math.radians(i)) * height + height)): c.set(x,y) for x in range(0, 360, 2): coords = (x/2, height + int(round(math.sin(math.radians(x+i)) * height))) c.set(*coords) f = c.frame() stdscr.addstr(0, 0, '{0}\n'.format(f)) stdscr.refresh() i += 2 sleep(1.0/24) c.clear()
def image2term(image, threshold=128, ratio=None, invert=False): if image.startswith('http://') or image.startswith('https://'): f = BytesIO(requests.get(image).content) i = Image.open(f).convert('L') else: with open(image, 'rb') as f: i = Image.open(f).convert('L') w, h = i.size if ratio: w = int(w * ratio) h = int(h * ratio) i = i.resize((w, h), Image.ANTIALIAS) else: tw = getTerminalSize()[0] tw *= 2 if tw < w: ratio = tw / float(w) w = tw h = int(h * ratio) i = i.resize((w, h), Image.ANTIALIAS) can = Canvas() x = y = 0 try: i_converted = i.tobytes() except AttributeError: i_converted = i.tostring() for pix in i_converted: if type(pix) is not int: pix = ord(pix) if invert: if pix > threshold: can.set(x, y) else: if pix < threshold: can.set(x, y) x += 1 if x >= w: y += 1 x = 0 return can.frame(0, 0)
async def handle_client(cls, process): pos = 0, 0 i = 0 process.stdout.write('\e[8;50;100t') while i < 1000: c = Canvas() process.stdout.write('\033[2J') process.stdout.write("\033[?25l") for i in range(pos[0], pos[0] + 10): for j in range(pos[1], pos[1] + 10): c.set(i % 80 - 40, j % 60 - 30) process.stdout.write(c.frame(-40, -30, 40, 30)) await asyncio.sleep(1. / 15) pos = pos[0] + 1, pos[1] + 1 i += 1 process.exit(0)
def draw_coords(stdscr, design): c = Canvas() for i in range(10): for point in design: c.set(point.x, point.y) df = c.frame(-40, -40, 80, 80) stdscr.addstr(1, 0, df) stdscr.refresh() new_move_delta = Point(choice([-1, 0, 1]), choice([-1, 0, 1])) design = move(design, new_move_delta) sleep(.5) c.clear() sleep(6) c.clear()
def __main__(projection=False): angleX, angleY, angleZ = 0, 0, 0 c = Canvas() while 1: # Will hold transformed vertices. t = [] for v in vertices: # Rotate the point around X axis, then around Y axis, and finally around Z axis. p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ) if projection: # Transform the point from 3D to 2D p = p.project(50, 50, 50, 50) # Put the point in the list of transformed vertices t.append(p) for f in faces: for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y): c.set(x, y) for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y): c.set(x, y) for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y): c.set(x, y) for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y): c.set(x, y) f = c.frame(-20, -20, 20, 20) s = 'broadcast "\\n\\n\\n' for l in format(f).splitlines(): s += l.replace(" ", " ").rstrip("\n") + "\\n" s = s[:-2] s += '"' print(s) sys.stdout.flush() angleX += 2 angleY += 3 angleZ += 5 sleep(1.0 / 10) c.clear()
def __main__(projection=False): angleX, angleY, angleZ = 0, 0, 0 c = Canvas() while 1: # Will hold transformed vertices. t = [] for v in vertices: # Rotate the point around X axis, then around Y axis, and finally around Z axis. p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ) if projection: # Transform the point from 3D to 2D p = p.project(50, 50, 50, 50) #Put the point in the list of transformed vertices t.append(p) for f in faces: for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y): c.set(x, y) for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y): c.set(x, y) for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y): c.set(x, y) for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y): c.set(x, y) f = c.frame(-20, -20, 20, 20) s = 'broadcast "\\n\\n\\n' for l in format(f).splitlines(): s += l.replace(' ', ' ').rstrip('\n') + '\\n' s = s[:-2] s += '"' print(s) sys.stdout.flush() angleX += 2 angleY += 3 angleZ += 5 sleep(1.0 / 10) c.clear()
def get_frame(terminal_width: int = 80) -> str: pixel_width = terminal_width * 2 cutoff = get_cutoff(pixel_width) base_path = path.dirname(__file__) world_path = path.abspath(path.join(base_path, "world.svg")) drawing = svg2rlg(world_path) image = renderPM.drawToPIL(drawing) height, width = image.size image = image.resize((pixel_width, int(width / height * pixel_width))) height, width = image.size canvas = Canvas() for x in range(0, height): for y in range(0, width): pixel = image.getpixel((x, y)) if pixel[0] < cutoff and pixel[1] < cutoff and pixel[2] < cutoff: canvas.set(x, y) return canvas.frame()
def image2term(image, threshold=128, ratio=None, invert=False): if image.startswith('http://') or image.startswith('https://'): i = Image.open(StringIO(urllib2.urlopen(image).read())).convert('L') else: i = Image.open(open(image)).convert('L') w, h = i.size if ratio: w = int(w * ratio) h = int(h * ratio) i = i.resize((w, h), Image.ANTIALIAS) else: tw = getTerminalSize()[0] tw *= 2 if tw < w: ratio = tw / float(w) w = tw h = int(h * ratio) i = i.resize((w, h), Image.ANTIALIAS) can = Canvas() x = y = 0 try: i_converted = i.tobytes() except AttributeError: i_converted = i.tostring() for pix in i_converted: if invert: if ord(pix) > threshold: can.set(x, y) else: if ord(pix) < threshold: can.set(x, y) x += 1 if x >= w: y += 1 x = 0 return can.frame(0, 0)
def to_txt(self, sep="\n", tw=240, invert=False, threshold=200): # import pdb; pdb.set_trace() buf = io.BytesIO() self.print_png(buf) buf.seek(0) i = Image.open(buf) w, h = i.size ratio = tw / float(w) w = tw h = int(h * ratio) i = i.resize((w, h), Image.ANTIALIAS) i = i.convert(mode="L") can = Canvas() for y in range(h): for x in range(w): pix = i.getpixel((x, y)) if invert: if pix > threshold: can.set(x, y) else: if pix < threshold: can.set(x, y) for x, y, s in self.renderer.texts: can.set_text(int(x * ratio), int(y * ratio), s) return can.frame()
def test_frame(self): c = Canvas() self.assertEqual(c.frame(), '') c.set(0, 0) self.assertEqual(c.frame(), 'РаЂ')
def test_set_text(self): c = Canvas() c.set_text(0, 0, "asdf") self.assertEqual(c.frame(), "asdf")
lt = left bk = back ########NEW FILE######## __FILENAME__ = basic from __future__ import print_function from drawille import Canvas import math s = Canvas() for x in range(1800): s.set(x/10, math.sin(math.radians(x)) * 10) print(s.frame()) s.clear() for x in range(0, 1800, 10): s.set(x/10, 10 + math.sin(math.radians(x)) * 10) s.set(x/10, 10 + math.cos(math.radians(x)) * 10) print(s.frame()) s.clear() for x in range(0, 3600, 20): s.set(x/20, 4 + math.sin(math.radians(x)) * 4) print(s.frame())
def view_protein(in_file, file_format=None, curr_model=1, chains=[], box_size=100.0): if box_size < 10.0 or box_size > 400.0: print("Box size must be between 10 and 400") return zoom_speed = 1.1 trans_speed = 1.0 rot_speed = 0.1 spin_speed = 0.01 action_count = 500 auto_spin = False cycle_models = False # Infer file format from extension if file_format is None: file_format = os.path.basename(in_file).rsplit(".", 1)[-1] # Handle stdin if in_file == "-": contents = sys.stdin.read() struct_file = StringIO(contents) try: # Redirect stdin from pipe back to terminal sys.stdin = open("/dev/tty", "r") except: print( "Piping structures not supported on this system (no /dev/tty)") return else: struct_file = in_file if file_format.lower() == "pdb": from Bio.PDB import PDBParser p = PDBParser() struc = p.get_structure("", struct_file) elif file_format.lower() in ("mmcif", "cif"): from Bio.PDB.MMCIFParser import MMCIFParser p = MMCIFParser() struc = p.get_structure("", struct_file) elif file_format.lower() == "mmtf": from Bio.PDB.mmtf import MMTFParser struc = MMTFParser.get_structure(struct_file) else: print("Unrecognised file format") return # Get backbone coordinates coords = [] connections = [] atom_counter, res_counter = 0, 0 chain_ids = [] for mi, model in enumerate(struc): model_coords = [] for chain in model: chain_id = chain.get_id() if len(chains) > 0 and chain_id not in chains: continue if mi == 0: chain_ids.append(chain_id) for res in chain: if mi == 0: res_counter += 1 res_n = res.get_id()[1] for atom in res: if mi == 0: atom_counter += 1 if atom.get_name() in ( "N", "CA", "C", # Protein "P", "O5'", "C5'", "C4'", "C3'", "O3'", # Nucleic acid ): if mi == 0 and len(model_coords) > 0: # Determine if the atom is connected to the previous atom connections.append(chain_id == last_chain_id and (res_n == (last_res_n + 1) or res_n == last_res_n)) model_coords.append(atom.get_coord()) last_chain_id, last_res_n = chain_id, res_n model_coords = np.array(model_coords) if mi == 0: if model_coords.shape[0] == 0: print("Nothing to show") return coords_mean = model_coords.mean(0) model_coords -= coords_mean # Center on origin of first model coords.append(model_coords) coords = np.array(coords) if curr_model > len(struc): print("Can't find that model") return info_str = "{} with {} models, {} chains ({}), {} residues, {} atoms".format( os.path.basename(in_file), len(struc), len(chain_ids), "".join(chain_ids), res_counter, atom_counter) # Make square bounding box of a set size and determine zoom x_min, x_max = float(coords[curr_model - 1, :, 0].min()), float(coords[curr_model - 1, :, 0].max()) y_min, y_max = float(coords[curr_model - 1, :, 1].min()), float(coords[curr_model - 1, :, 1].max()) x_diff, y_diff = x_max - x_min, y_max - y_min box_bound = float(np.max([x_diff, y_diff])) + 2.0 zoom = box_size / box_bound x_min = zoom * (x_min - (box_bound - x_diff) / 2.0) x_max = zoom * (x_max + (box_bound - x_diff) / 2.0) y_min = zoom * (y_min - (box_bound - y_diff) / 2.0) y_max = zoom * (y_max + (box_bound - y_diff) / 2.0) # See https://stackoverflow.com/questions/13207678/whats-the-simplest-way-of-detecting-keyboard-input-in-python-from-the-terminal/13207724 fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) canvas = Canvas() trans_x, trans_y = 0.0, 0.0 rot_x, rot_y = 0.0, 0.0 try: while True: os.system("clear") points = [] for x_start, y_start, x_end, y_end in ( (x_min, y_min, x_max, y_min), (x_max, y_min, x_max, y_max), (x_max, y_max, x_min, y_max), (x_min, y_max, x_min, y_min), ): for x, y in line(x_start, y_start, x_end, y_end): points.append([x, y]) rot_mat_x = np.array([ [1.0, 0.0, 0.0], [0.0, np.cos(rot_x), -np.sin(rot_x)], [0.0, np.sin(rot_x), np.cos(rot_x)], ], dtype=np.float32) rot_mat_y = np.array([ [np.cos(rot_y), 0.0, np.sin(rot_y)], [0.0, 1.0, 0.0], [-np.sin(rot_y), 0.0, np.cos(rot_y)], ], dtype=np.float32) trans_coords = coords[curr_model - 1] + np.array( [trans_x, trans_y, 0.0], dtype=np.float32) zoom_rot_coords = zoom * np.matmul( rot_mat_y, np.matmul(rot_mat_x, trans_coords.T)).T for i in range(coords.shape[1] - 1): if connections[i]: x_start, x_end = float(zoom_rot_coords[i, 0]), float( zoom_rot_coords[i + 1, 0]) y_start, y_end = float(zoom_rot_coords[i, 1]), float( zoom_rot_coords[i + 1, 1]) if x_min < x_start < x_max and x_min < x_end < x_max and y_min < y_start < y_max and y_min < y_end < y_max: for x, y in line(x_start, y_start, x_end, y_end): points.append([x, y]) print(info_str) print( "W/A/S/D rotates, T/F/G/H moves, I/O zooms, U spins, P cycles models, Q quits" ) canvas.clear() for x, y in points: canvas.set(x, y) print(canvas.frame()) counter = 0 while True: if auto_spin or cycle_models: counter += 1 if counter == action_count: if auto_spin: rot_y += spin_speed if cycle_models: curr_model += 1 if curr_model > len(struc): curr_model = 1 break try: k = sys.stdin.read(1) if k: if k.upper() == "O": zoom /= zoom_speed elif k.upper() == "I": zoom *= zoom_speed elif k.upper() == "F": trans_x -= trans_speed elif k.upper() == "H": trans_x += trans_speed elif k.upper() == "G": trans_y -= trans_speed elif k.upper() == "T": trans_y += trans_speed elif k.upper() == "S": rot_x -= rot_speed elif k.upper() == "W": rot_x += rot_speed elif k.upper() == "A": rot_y -= rot_speed elif k.upper() == "D": rot_y += rot_speed elif k.upper() == "U": auto_spin = not auto_spin elif k.upper() == "P" and len(struc) > 1: cycle_models = not cycle_models elif k.upper() == "Q": return break except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
def printa_parabola(lado): s = Canvas() s.clear() for x in range(0, 180): s.set(x / 4, lado + sin(radians(x)) * lado) return s.frame()
from __future__ import print_function from drawille import Canvas from math import sin, radians c = Canvas() for x in range(0, 1800, 2): c.set(x / 20, 10 + sin(radians(x)) * 10) print(c.frame())
def test_max_min_limits(self): c = Canvas() c.set(0, 0) self.assertEqual(c.frame(min_x=2), '') self.assertEqual(c.frame(max_x=0), '')
else: url = 'http://xkcd.com/%s/' % argv[1] c = urllib2.urlopen(url).read() img_url = re.findall('http:\/\/imgs.xkcd.com\/comics\/.*\.png', c)[0] i = Image.open(StringIO(urllib2.urlopen(img_url).read())).convert('L') w, h = i.size tw, th = getTerminalSize() tw *= 2 th *= 2 if tw < w: ratio = tw / float(w) w = tw h = int(h * ratio) i = i.resize((w, h), Image.ANTIALIAS) can = Canvas() x = y = 0 try: i_converted = i.tobytes() except AttributeError: i_converted = i.tostring() for pix in i_converted: if ord(pix) < 128: can.set(x, y) x += 1 if x >= w: y += 1 x = 0 print(can.frame())
if (dither or trippy) : #because you can't divide by zero if (sum == 0) : canvo.unset(x,y) else: #the RGB scale is exponential , so the ratio of light from 255 to 80 would be 255^2/80^2 # however since the image is 3 dimensional, then the dither turns on in 1/mod * 1/mod # so mod should be 255/80 instead mod = int(255 / sum) # the ratio here is (2x-1)/x^2 where x is 255/sum if (trippy) : if (((x % mod) == 0) or ((y % mod) == 0)) : canvo.set(x,y) else: canvo.unset(x,y) #ratio is 1/x^2 elif (dither) : if (((x % mod) == 0) and ((y % mod) == 0)) : canvo.set(x,y) else: canvo.unset(x,y) else: if (threshup >= sum >= threshdown ) : # turns the dot on at x,y canvo.set(x,y) else : # it seems if an entire character is blank, draille does not print it regardless of this canvo.unset(x,y) #prints the final product print(canvo.frame())
def view(in_file, file_format=None, curr_model=1, chains=[], box_size=100.0): if box_size < 10.0 or box_size > 400.0: print("Box size must be between 10 and 400") return auto_spin = False cycle_models = False coords, info = read_inputs(in_file, file_format, curr_model, chains) if coords is None: return # Build help strings info_str = ( f"{os.path.basename(in_file)} with {info['num_struc']} models, " f"{len(info['chain_ids'])} chains ({''.join(info['chain_ids'])}) " f"{info['res_counter']} residues, {info['atom_counter']} atoms.") help_str = "W/A/S/D rotates, T/F/G/H moves, I/O zooms, U spins, P cycles models, Q quits" # Make square bounding box of a set size and determine zoom x_min, x_max = float(coords[curr_model - 1, :, 0].min()), float(coords[curr_model - 1, :, 0].max()) y_min, y_max = float(coords[curr_model - 1, :, 1].min()), float(coords[curr_model - 1, :, 1].max()) x_diff, y_diff = x_max - x_min, y_max - y_min box_bound = float(np.max([x_diff, y_diff])) + 2.0 zoom = box_size / box_bound x_min = zoom * (x_min - (box_bound - x_diff) / 2.0) x_max = zoom * (x_max + (box_bound - x_diff) / 2.0) y_min = zoom * (y_min - (box_bound - y_diff) / 2.0) y_max = zoom * (y_max + (box_bound - y_diff) / 2.0) # Set up curses screen # https://docs.python.org/3/howto/curses.html stdscr = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(False) stdscr.keypad(True) # Respond to keypresses w/o Enter stdscr.nodelay(True) # Don't block while waiting for keypress # Divide curses screen into windows window_info = stdscr.subwin( 2, curses.COLS - 1, # height, width 0, 0) # begin_y, begin_x window_structure = stdscr.subwin( curses.LINES - 1 - 2, curses.COLS - 1, # height, width 2, 0) # begin_y, begin_x # Print help strings (only need to do this once) window_info.addnstr(0, 0, info_str, window_info.getmaxyx()[1] - 1) window_info.addnstr(1, 0, help_str, window_info.getmaxyx()[1] - 1) window_info.refresh() canvas = Canvas() trans_x, trans_y = 0.0, 0.0 rot_x, rot_y = 0.0, 0.0 try: points = [] do_update = True while True: curses.napms(50) # Delay a short while # Re-draw structure if needed if do_update: points = [] for x_start, y_start, x_end, y_end in ( (x_min, y_min, x_max, y_min), (x_max, y_min, x_max, y_max), (x_max, y_max, x_min, y_max), (x_min, y_max, x_min, y_min), ): for x, y in line(x_start, y_start, x_end, y_end): points.append([x, y]) rot_mat_x = np.array([ [1.0, 0.0, 0.0], [0.0, np.cos(rot_x), -np.sin(rot_x)], [0.0, np.sin(rot_x), np.cos(rot_x)], ], dtype=np.float32) rot_mat_y = np.array([ [np.cos(rot_y), 0.0, np.sin(rot_y)], [0.0, 1.0, 0.0], [-np.sin(rot_y), 0.0, np.cos(rot_y)], ], dtype=np.float32) trans_coords = coords[curr_model - 1] + np.array( [trans_x, trans_y, 0.0], dtype=np.float32) zoom_rot_coords = zoom * np.matmul( rot_mat_y, np.matmul(rot_mat_x, trans_coords.T)).T for i in range(coords.shape[1] - 1): if not info['connections'][i]: continue x_start, x_end = float(zoom_rot_coords[i, 0]), float( zoom_rot_coords[i + 1, 0]) y_start, y_end = float(zoom_rot_coords[i, 1]), float( zoom_rot_coords[i + 1, 1]) # Check if the bond fits in the box if x_min < x_start < x_max and x_min < x_end < x_max and y_min < y_start < y_max and y_min < y_end < y_max: for x, y in line(x_start, y_start, x_end, y_end): points.append([x, y]) # Update displayed structure canvas.clear() for x, y in points: canvas.set(x, y) window_structure.addstr(0, 0, canvas.frame()) window_structure.refresh() do_update = False # Prepare rotation/model selection for next time if auto_spin: rot_y += spin_speed do_update = True if cycle_models: curr_model += 1 if curr_model > len(coords): curr_model = 1 do_update = True # Handle keypresses try: c = stdscr.getch() if c != curses.ERR: do_update = True if c in (ord("o"), ord("O")): zoom /= zoom_speed elif c in (ord("i"), ord("I")): zoom *= zoom_speed elif c in (ord("f"), ord("F")): trans_x -= trans_speed elif c in (ord("h"), ord("H")): trans_x += trans_speed elif c in (ord("g"), ord("G")): trans_y -= trans_speed elif c in (ord("t"), ord("T")): trans_y += trans_speed elif c in (ord("s"), ord("S")): rot_x -= rot_speed elif c in (ord("w"), ord("W")): rot_x += rot_speed elif c in (ord("a"), ord("A")): rot_y -= rot_speed elif c in (ord("d"), ord("D")): rot_y += rot_speed elif c in (ord("u"), ord("U")): auto_spin = not auto_spin elif c in (ord("p"), ord("P")) and len(coords) > 1: cycle_models = not cycle_models elif c in (ord("q"), ord("Q")): return except IOError: pass except KeyboardInterrupt: # If user presses Ctrl+C, pretend as if they pressed q. return finally: # Teardown curses interface curses.nocbreak() curses.echo() curses.curs_set(True) stdscr.keypad(False) curses.endwin() # Make sure last view stays on screen print(info_str) print(help_str) print(canvas.frame())
from __future__ import print_function from drawille import Canvas import math canvas = Canvas() for x in range(1800): canvas.set(x / 10, math.sin(math.radians(x)) * 10) print(canvas.frame()) canvas.clear() for x in range(0, 1800, 10): canvas.set(x / 10, 10 + math.sin(math.radians(x)) * 10) canvas.set(x / 10, 10 + math.cos(math.radians(x)) * 10) print(canvas.frame()) canvas.clear() for x in range(0, 3600, 20): canvas.set(x / 20, 4 + math.sin(math.radians(x)) * 4) print(canvas.frame()) canvas.clear() for x in range(0, 360, 4): canvas.set(x / 4, 30 + math.sin(math.radians(x)) * 30)
from __future__ import print_function from drawille import Canvas import math s = Canvas() for x in range(1800): s.set((x/10, math.sin(math.radians(x)) * 10)) print(s.frame()) s.clear() for x in range(0, 1800, 10): s.set((x/10, 10 + math.sin(math.radians(x)) * 10)) s.set((x/10, 10 + math.cos(math.radians(x)) * 10)) print(s.frame()) s.clear() for x in range(0, 3600, 20): s.set((x/20, 4 + math.sin(math.radians(x)) * 4)) print(s.frame()) s.clear() for x in range(0, 360, 4): s.set((x/4, 30 + math.sin(math.radians(x)) * 30))
class GameOfLife: def __init__(self, rows, cols): self.rows = rows self.cols = cols self.can = Canvas() self.state = [[bool(random.getrandbits(1)) for y in range(rows)] for x in range(cols)] def tick(self): next_gen = [[False for y in range(self.rows)] for x in range(self.cols)] for y in range(self.rows): for x in range(self.cols): nburs = self._ncount(x, y) if self.state[x][y]: # Alive if nburs > 1 and nburs < 4: self.can.set(x,y) next_gen[x][y] = True else: next_gen[x][y] = False else: # Dead if nburs == 3: self.can.set(x,y) next_gen[x][y] = True else: next_gen[x][y] = False self.state = next_gen def draw(self): f = self.can.frame(0,0,self.cols,self.rows) stdscr.addstr(0, 0, '{0}\n'.format(f)) self.can.clear() def put(self, matrix, x, y): for mx in range(len(matrix)): for my in range(len(matrix[0])): self.state[min(x+my,self.cols-1)][min(y+mx,self.rows-1)] = matrix[mx][my] def _ncount(self, x, y): nburs = 0 # Left if x > 0: if self.state[x-1][y]: nburs += 1 # Top if y > 0: if self.state[x-1][y-1]: nburs += 1 # Bottom if y < self.rows-1: if self.state[x-1][y+1]: nburs += 1 # Right if x < self.cols-1: if self.state[x+1][y]: nburs += 1 # Top if y > 0: if self.state[x+1][y-1]: nburs += 1 # Bottom if y < self.rows-1: if self.state[x+1][y+1]: nburs += 1 # Top if y > 0: if self.state[x][y-1]: nburs += 1 # Bottom if y < self.rows-1: if self.state[x][y+1]: nburs += 1 return nburs
'titles': info['num'], 'redirects': 'true', 'format': 'json', })) redirect_request = Request(redirect_url, headers={'User-Agent': 'xkcd CLI tool'}) redirect_json = urlopen(redirect_request).read().decode('utf-8') redirect = json.loads(redirect_json) redirect_to = redirect['query']['redirects'][0]['to'] transcription_url = "https://www.explainxkcd.com/wiki/api.php?{}".format(urlencode({ 'action': 'parse', 'page': redirect_to, 'prop': 'text', 'section': 2, 'format': 'json', 'disableeditsection': 'true', })) transcription_request = Request(transcription_url, headers={'User-Agent': 'xkcd CLI tool'}) transcription_json = urlopen(transcription_request).read().decode('utf-8') transcription = json.loads(transcription_json) """ print(("\033[92m{0}: {1}\033[0m".format(info['num'], info['title']))) print((can.frame())) print(('')) print(("\033[1;31mAlt text\033[0m: {0}".format(info['alt']))) print(('')) print(("\033[1;31mOriginal\033[0m: \033[96mhttps://xkcd.com/{0}\033[0m".format(info['num']))) print(("\033[1;31mExplanation\033[0m: \033[96mhttps://www.explainxkcd.com/wiki/index.php/{0}\033[0m".format(info['num']))) print((''))
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from drawille import Canvas import math s = Canvas() for x in range(1800): s.set(x / 10, math.sin(math.radians(x)) * 10) print(s.frame()) s.clear() for x in range(0, 1800, 10): s.set(x / 10, 10 + math.sin(math.radians(x)) * 10) s.set(x / 10, 10 + math.cos(math.radians(x)) * 10) print(s.frame()) s.clear() for x in range(0, 3600, 20): s.set(x / 20, 4 + math.sin(math.radians(x)) * 4) print(s.frame()) s.clear()
def main(): last_graph_y = None with open('grades_db.json', 'r') as db: grades = json.loads(db.read()) headers = [] spacing_formats = [] color_formats = [] headers.append('%') spacing_formats.append('{: <7}') color_formats.append('\033[0;32m' + '{}' + Style.RESET_ALL + Fore.RESET) headers.append('assignment') spacing_formats.append('{: <50}') color_formats.append('\033[0;33m' + '{}' + Style.RESET_ALL + Fore.RESET) headers.append('multiplier') spacing_formats.append('{: <12}') color_formats.append(Style.DIM + '\033[2;34m' + '{}' + Style.RESET_ALL + Fore.RESET) headers.append('score') spacing_formats.append('{: <8}') color_formats.append(Fore.MAGENTA + '{}' + Style.RESET_ALL + Fore.RESET) headers.append('out of') spacing_formats.append('{: <8}') color_formats.append(Fore.MAGENTA + '{}' + Style.RESET_ALL + Fore.RESET) headers.append('due') spacing_formats.append('{: <11}') color_formats.append(Style.DIM + '{}' + Style.RESET_ALL + Fore.RESET) headers.append('assigned') spacing_formats.append('{: <11}') color_formats.append(Style.DIM + '{}' + Style.RESET_ALL + Fore.RESET) for class_name in grades: class_ = grades[class_name] teacher = class_['teacher'] grade = class_['grade'] print '\033[4;36m' + class_name + Fore.RESET + Style.RESET_ALL print '\033[2;4;36m' + teacher + Fore.RESET + Style.RESET_ALL print '\033[34m' + str(grade) + Fore.RESET + Style.RESET_ALL print '' if grade is 'None': print '\n' * 2 continue print Style.BRIGHT + ' '.join(spacing_formats).format( *headers) + Style.RESET_ALL print '' for section_name in class_['sections']: section = class_['sections'][section_name] c = Canvas() x = 0 print('\033[4;31m' + section_name + Style.RESET_ALL).ljust(60) + ' - ' + section['weight'] + '%' graph_spacing = int( terminal_columns / len(section['assignments'])) * 2 for assignment in section['assignments']: data_columns = assignment data_values = [data_columns[key] for key in headers] try: val = 100 - float(data_columns['%']) if last_graph_y is not None: diff = last_graph_y - val for x_ in range((x - 1) * graph_spacing, x * graph_spacing): progress = x_ - x * graph_spacing c.set(x_, val - diff * progress / graph_spacing) # pass c.set(x * graph_spacing, val) last_graph_y = val except: pass x += 1 for value, color_format, spacing_format in zip( data_values, spacing_formats, color_formats): print spacing_format.format(color_format.format(value)), print '' print '' print(c.frame()) print '\n' * 2