def view(string, entities): response = requests.get(util.config("quoteData")) data = response.json() quoteNumber = 111 for item in entities: if item["entity"] == "quote" or item["entity"] == "id" or item[ "entity"] == "number": quoteNumber = item["utteranceText"].lower().strip() quote = data["quotes"][int(quoteNumber) - 1] if quote is None: return util.output( "end", "quote_doesnt_exist", util.translate("quote_doesnt_exist", {"ID": quoteNumber})) # TODO: quote side_text return util.output( "end", "quote", util.translate("quote", { "ID": quoteNumber, "author": quote["user"], "text": quote["text"] }))
def grow_cell(self): if len(self.cells) > 100: return # Get a random point position = self.bounds.get_random_point() self.last_guess = position # Search for the nearest cell nearestNeighbor = forest.bestNN(position, self.kd_tree) distance = forest.distance(nearestNeighbor.point, position) center = self.bounds.get_center() dx = position[0] - center[0] dy = position[1] - center[1] angle = math.degrees(math.atan2(dy, dx)) hue = util.translate(angle, -180, 180, 0, 1) value = 1 - util.translate(forest.distance(center, position), 0, 500, 0, 1) color = colorsys.hsv_to_rgb(hue, .9, value) # Lookup cell cell = self.cells[nearestNeighbor.point] # If the new point happens to be in range of our closest neighbor if cell.size <= distance <= self.envelope: new_cell = Cell(position=position, color=color) self.kd_tree = forest.insert_point(self.kd_tree, position) self.cells[position] = new_cell
def draw(i): state = "rotate" rotate = 0 advance = 0 print(i) for j in range(i): if state == "rotate": rotate += np.pi * 0.5 * 0.1 if rotate >= np.pi * 0.5: rotate = 0 state = "advance" elif state == "advance": advance = util.translate([0, advance], [0, -0.02])[1] finish = _translate_tile([0, 0], "d" * step, tile_size=tile_size)[1] if finish > advance: advance = finish state = "finish" if state == "finish": print("finish") t_tiles = util.rotate(tiles, rotate) t_tiles = util.translate(t_tiles, [0, advance]) plt.cla() util.draw_circle() plt.plot(t_tiles[:, :, 0].T, t_tiles[:, :, 1].T, lw=0.5, color="blue") _plot_xy(marker, color="red", lw=1)
def _make_line(x, y, n=4): x = np.asarray(x) y = np.asarray(y) dy = util.translate(y, -x) lin = np.linspace(0, 1, n)[:, None] * dy[None, :] return util.translate(lin, x)
def assign(self, target: AstNode, value): """Assigns the specified value to the target (either variable or array access).""" if isinstance(target, IdentifierNode): self.evaluator.set_variable(target.value, value) elif isinstance(target, ArrayAccessNode): array = self.evaluator.eval_node(target.array) if not type(array) == list: self.log.error( translate("Algo", "Array access target must be of array type")) self.finish() return index = self.evaluator.eval_node(target.index) while index >= len(array): array.append(0) if index < len(array): array[index] = value else: self.log.error( translate( "Algo", "Index '{idx}' too big for array").format(idx=index)) return None else: self.log.error( translate( "Algo", "Assignment target must be either variable or array item")) self.finish() return
def placeStruts(axis): orientation = p.getQuaternionFromEuler([i * ut.PI/2 for i in axis]) if axis == X: axis = Z elif axis == Z: axis = X center1 = ut.translate([i * OFFSET for i in axis], POSITION) center2 = ut.translate([-i * OFFSET for i in axis], POSITION) return (center1, orientation), (center2, orientation)
def cal_mds_positions(self, src=None, tgt=None): (matrix, m) = self.cal_edge_weight_matrix(src, tgt) p = MDSLayout.cal_mds(matrix, m) x_min = min(map(lambda e: e[0], p)) x_max = max(map(lambda e: e[0], p)) y_min = min(map(lambda e: e[1], p)) y_max = max(map(lambda e: e[1], p)) for i, e in enumerate(self.nx_g.nodes()): self.nx_g.node[e]["x"] = translate(p[i][0], x_min, x_max, 0, self.width) self.nx_g.node[e]["y"] = translate(p[i][1], y_min, y_max, 0, self.height)
def failed_pattern(line, pattern, verbose, buildtool=None): global must_restart pat = re.compile(pattern) match = pat.search(line) if not match: return s = match.group(1) try: if not buildtool: req = config.failed_commands[s] if req: must_restart += buildreq.add_buildreq(req) elif buildtool == 'pkgconfig': must_restart += buildreq.add_pkgconfig_buildreq(s) elif buildtool == 'R': if buildreq.add_buildreq("R-" + s) > 0: must_restart += 1 buildreq.add_requires("R-" + s) elif buildtool == 'perl': must_restart += buildreq.add_buildreq('perl(%s)' % s) elif buildtool == 'pypi': s = util.translate(s) if not s: return must_restart += buildreq.add_buildreq( util.translate('%s-python' % s)) elif buildtool == 'ruby': if s in config.gems: must_restart += buildreq.add_buildreq(config.gems[s]) else: must_restart += buildreq.add_buildreq('rubygem-%s' % s) elif buildtool == 'ruby table': if s in config.gems: must_restart += buildreq.add_buildreq(config.gems[s]) else: print("Unknown ruby gem match", s) elif buildtool == 'maven': if s in config.maven_jars: must_restart += buildreq.add_buildreq(config.maven_jars[s]) else: must_restart += buildreq.add_buildreq('jdk-%s' % s) elif buildtool == 'catkin': must_restart += buildreq.add_pkgconfig_buildreq(s) must_restart += buildreq.add_buildreq(s) except: if verbose > 0: print("Unknown pattern match: ", s)
def failed_pattern_pypi(line, pattern, verbose=0): global must_restart global failed_commands pat = re.compile(pattern) match = pat.search(line) if match: s = util.translate(match.group(1)) if s == "": return try: must_restart = must_restart + buildreq.add_buildreq(util.translate('%s-python' % s)) except: if verbose > 0: print("Unknown python pattern match: ", pattern, s, line)
def clean_python_req(req, add_python=True): """ Strip version information from req """ if req.find("#") == 0: return "" ret = req.rstrip("\n\r").strip() i = ret.find("<") if i > 0: ret = ret[:i] i = ret.find("\n") if i > 0: ret = ret[:i] i = ret.find(">") if i > 0: ret = ret[:i] i = ret.find("=") if i > 0: ret = ret[:i] i = ret.find("#") if i > 0: ret = ret[:i] i = ret.find("!") if i > 0: ret = ret[:i] ret = ret.strip() # is ret actually a valid (non-empty) string? if ret and add_python: ret = ret.strip() # use the dictionary to translate funky names to our current pgk names ret = util.translate(ret) return ret
def exec_input(self, stmt: InputStmt): """Executes an input statement.""" prompt = (translate("Algo", "Variable {var} = ").format( var=stmt.variable.code()) ) if stmt.prompt is None else self.evaluator.eval_node( stmt.prompt) self.assign(stmt.variable, self.stmt_input(prompt, stmt.text))
def getUserInfo(user): if user.has_attribute(ATTR_NUMBER): external, internal = parseTelephoneAttr(get_attr_value(user, ATTR_NUMBER)) else: external = internal = None mobileNumber = get_attr_value(user, ATTR_MOBILE_NUMBER) mobileNumber = formatExternalNumber(mobileNumber[0]) if mobileNumber is not None else None telephoneNumber = get_attr_value(user, ATTR_TELEPHONE_NUMBER) telephoneNumber = telephoneNumber if is_valid_internal_number(telephoneNumber) else None user_info = dict( uid=get_attr_value(user, ATTR_UID), firstName=get_attr_value(user, ATTR_FIRST_NAME), lastName=get_attr_value(user, ATTR_LAST_NAME), ou=get_attr_value(user, ATTR_OU), mobileNumber=mobileNumber, telephoneNumber=telephoneNumber, externalNumber=external, internalNumber=internal) for key, value in user_info.items(): if value is not None: value = value.decode('utf-8') value = util.translate(value) user_info[key] = value return user_info
def test_translate(self): """ Spot-test the translate function with a package defined in translate.dic """ self.assertEqual(util.translate('dateutil-python'), 'pypi-python_dateutil')
def clean_python_req(str, add_python=True): if str.find("#") == 0: return "" ret = str.rstrip("\n\r").strip() i = ret.find("<") if i > 0: ret = ret[:i] i = ret.find("\n") if i > 0: ret = ret[:i] i = ret.find(">") if i > 0: ret = ret[:i] i = ret.find("=") if i > 0: ret = ret[:i] i = ret.find("#") if i > 0: ret = ret[:i] i = ret.find("!") if i > 0: ret = ret[:i] ret = ret.strip() # is ret actually a valid (non-empty) string? if ret and add_python: ret = ret.strip() + "-python" # use the dictionary to translate funky names to our current pgk names ret = util.translate(ret) return ret
def getWeather(entities, owm): for item in entities: if item["entity"] == "city": util.output( "intermediate", "fetching", util.translate("fetching", {"city": item["sourceText"]})) city = item["sourceText"] report = owm.weather_manager().weather_at_place(city) weather = report.weather val = {"city": city, "report": report, "weather": weather} return val return util.output("end", "error", util.translate("error"))
def python(self) -> List[str]: return [ "%s = input(%s)" % (self.variable.python(), ('"%s"' % translate("Algo", "Variable {var} = ").format( var=self.variable.python())) if self.prompt is None else self.prompt.python()) ]
def expect_token(self, token_type: TokenType, value=None): """Asserts the next token is of the specified type and (optional) value. Explodes otherwise.""" if not self.match_token(token_type, value): self.log.error( translate("Parser", "Expected token ({type}) '{val}'").format( type=TokenType.get_name(token_type), val=value)) return None return self.next_token()
def _verify(in_aa, out_str): out_aa= util.translate(out_str) if out_aa != in_aa: print("in : {}".format(in_aa)) print("out: {}".format(out_aa)) raise ValueError("Optimisation failed: translations don't match") return out_str
def get_color(color: str) -> str: """Converts the specified Algobox color to a standard CSS X11 color.""" lut = {"Bleu": "blue", "Rouge": "red", "Vert": "green", "Blanc": "white"} if color not in lut: raise ValueError( translate("Algobox", "Unknown color: {color}").format(color=color)) return lut[color]
def conversation(string, entities): testFeature = "" for item in entities: if item["entity"] == "feature": testFeature = item["utteranceText"].lower().strip() return util.output( "end", "conversation", util.translate("conversation", {"feature": testFeature}))
def temperature_city(source, entities): report = getWeather(entities, getOWM()) temperature = report["weather"].temperature("celsius") return util.output( "end", "temperature", util.translate("temperature", { "city": report["city"], "temperature": temperature["temp"] }))
def handleVideoInfo(videoInfo): try: # Create video folder videoDir = "H:\\自媒体\\2019-02" # + videoInfo['uploadDate'][:10] checkAndCreateFolder(videoDir) # Translate name and description name = util.translate(videoInfo['name']) desc = util.translate(videoInfo['description']) url = videoInfo['contentUrl'] duration = videoInfo['duration'] videoPath = videoDir + "\\" + name + ".mp4" descPath = videoDir + "\\" + name + ".txt" #download video downloadVideo(url, videoPath) # write desc checkAndCreateDescFile(descPath, name, desc) except: util.log(json.dumps(videoInfo))
def proper_str(a: Any) -> str: """Converts the specified float to string, removing comma if the number is integral.""" if type(a) == list: return "[%s]" % ", ".join(proper_str(x) for x in a) if not is_num(a): return str(a) if is_bool(a): return translate("Utilities", "TRUE") if a else translate( "Utilities", "FALSE") if type(a) == complex: real = None if is_zero(a.real) else proper_str(a.real) if a.imag == 1: imag = "i" elif a.imag != 0: s = proper_str(a.imag) if s != "0": imag = proper_str(a.imag) + "i" else: imag = None else: imag = None if real == imag is None: return "0" return " + ".join(x for x in [real, imag] if x) if abs(a) == float("inf"): return str(a) if abs(a) > 1e15 and int(float(a)) == a: a = float(a) elif is_int(a): return str(round(a)) if "e" in str(a): sig, exp = str(a).split("e") if int(exp) > 15 or int(exp) < -4: return str(sig) + "e" + str(int(exp)) return str(a)
def parse_term(self) -> Optional[nodes.AstNode]: """Parses an atomic term.""" if self.match_token(TokenType.NUMBER): return nodes.NumberNode(self.next_token()[1]) elif self.match_token(TokenType.BOOLEAN): return nodes.NumberNode(bool(self.next_token()[1])) elif self.match_token(TokenType.STRING): return nodes.StringNode(self.next_token()[1]) elif self.match_token(TokenType.IDENTIFIER): return nodes.IdentifierNode(self.next_token()[1]) elif self.accept_token(TokenType.PAREN, "("): stmt = self.parse_expression() self.expect_token(TokenType.PAREN, ")") return stmt elif self.match_token(TokenType.BRACK, "["): stmt = nodes.ListNode(self.parse_arg_list(True)) return stmt elif self.match_token(TokenType.BRACE, "{"): args = self.parse_param_list() self.expect_token(TokenType.PAREN, "(") expr = self.parse_expression() self.expect_token(TokenType.PAREN, ")") return nodes.LambdaNode(args, expr) else: if not self.can_read(): self.log.error(translate("Parser", "Unexpected EOL")) else: self.log.error( translate( "Parser", "Unexpected token ({type}) '{val}'").format( type=TokenType.get_name(self.peek_token()[0]), val=self.peek_token()[1])) return None
def fit_uv_mesh(initial_mesh: dict, target_dataset, max_iterations: int = 5000, resolution: int = 4, log_interval: int = 10, dispaly_interval=1000, display_res=512, out_dir=None, mp4save_interval=None): glctx = dr.RasterizeGLContext() r_rot = util.random_rotation_translation(0.25) # Smooth rotation for display. ang = 0.0 a_rot = np.matmul(util.rotate_x(-0.4), util.rotate_y(ang)) dist = 2 # Modelview and modelview + projection matrices. proj = util.projection(x=0.4, n=1.0, f=200.0) r_mv = np.matmul(util.translate(0, 0, -1.5 - dist), r_rot) r_mvp = np.matmul(proj, r_mv).astype(np.float32) a_mv = np.matmul(util.translate(0, 0, -3.5), a_rot) a_mvp = np.matmul(proj, a_mv).astype(np.float32) pos_idx = initial_mesh['pos_idx'].cuda() vtx_pos = initial_mesh['vtx_pos'].cuda() tex = np.ones((1024, 1024, 3), dtype=np.float32) / 2 uv, uv_idx = init_uv() uv_idx = uv_idx[:pos_idx.shape[0]] pos_idx = torch.from_numpy(pos_idx.astype(np.int32)).cuda() vtx_pos = torch.from_numpy(pos.astype(np.float32)).cuda() uv_idx = torch.from_numpy(uv_idx.astype(np.int32)).cuda() vtx_uv = torch.from_numpy(uv.astype(np.float32)).cuda() tex = torch.from_numpy(tex.astype(np.float32)).cuda() # Render reference and optimized frames. Always enable mipmapping for reference. color = render(glctx, r_mvp, vtx_pos, pos_idx, vtx_uv, uv_idx, tex, 1024, False, 0) Image.fromarray((color[0].detach().cpu().numpy() * 255).astype( np.uint8)).save('test.png')
def sunset_city(source, entities): report = getWeather(entities, getOWM()) datetime = report["weather"].sunset_time(("date")) datetime = datetime.astimezone(get_localzone()) return util.output( "end", "sunset", util.translate("sunset", { "time": datetime.strftime("%H:%M:%S"), "city": report["city"] }))
def exec_break(self, stmt: BreakStmt): """Executes a break statement.""" if not self.find_parent(Loops): self.log.error( translate("Algo", "BREAK can only be used inside a loop")) self.finish() return while True: if isinstance(self.exit_block()[0], Loops): break
def exec_else(self, stmt: ElseStmt): """Executes an else block.""" if self.if_status is None: self.log.error( translate("Algo", "ELSE can only be used after an IF block")) self.finish() return if not self.if_status[1]: self.enter_block(stmt) self.if_status = None
def clean_python_req(req): """Strip version information from req.""" if not req: return "" if req[0] == "#": return "" ret = req.rstrip("\n\r").strip() i = ret.find(";") if i >= 0: if old_python_module(ret): return "" else: ret = ret[:i] i = ret.find("<") if i >= 0: ret = ret[:i] i = ret.find("\n") if i >= 0: ret = ret[:i] i = ret.find(">") if i >= 0: ret = ret[:i] i = ret.find("=") if i >= 0: ret = ret[:i] i = ret.find("#") if i >= 0: ret = ret[:i] i = ret.find("!") if i >= 0: ret = ret[:i] i = ret.find("[") if i >= 0: ret = ret[:i] i = ret.find("~") if i >= 0: ret = ret[:i] i = ret.find(" ") if i >= 0: ret = ret[:i] ret = ret.strip() # use the dictionary to translate funky names to our current pgk names ret = util.translate(ret) if ret: # normalize to pypi name ret = pypidata.get_pypi_name(ret, miss=True) if ret and ret[0] == '_': # These tend to be leftover junk # ignore them ret = "" return ret
def exec_continue(self, stmt: ContinueStmt): """Executes a continue statement.""" if not self.find_parent(Loops): self.log.error( translate("Algo", "CONTINUE can only be used inside a loop")) self.finish() return while not isinstance(self.stack[-1][0], Loops): self.exit_block() stmt, index = self.stack[-1] index = len(stmt.children) self.stack[-1] = stmt, index
def parse(self) -> Optional[nodes.AstNode]: """Main parsing routine.""" self.tokenize() result = self.parse_expression() if self.can_read(): self.log.error( translate( "Parser", "Unexpected token ({type}) '{val}' after end of expression" ).format(type=TokenType.get_name(self.peek_token()[0]), val=self.peek_token()[1])) return None return result
def exec_return(self, stmt: ReturnStmt): """Executes a return statement.""" if not self.find_parent(FuncStmt): self.log.error( translate("Algo", "RETURN can only be used inside a function")) self.finish() return self.calls.append( self.evaluator.eval_node(stmt.value) if stmt.value else None) while True: if isinstance(self.exit_block()[0], FuncStmt): break
def create(string, entities): content = None if ("reply" in util.getQuery()["extra"]): content = util.getQuery()["extra"]["reply"]["content"] if not content: return util.output("end", "empty_paste", util.translate("empty_paste")) query = {"apikey": util.config("apikey")} payload = { "text": content, "title": "Automatic Upload", "name": "Guinevere" } request = requests.post("https://paste.gemwire.uk/api/create", params=query, data=payload) url = request.text.strip() return util.output("end", "paste_made", util.translate("paste_made", {"paste": url}))
def __keypress__(self, event): if event.keysym == 'Return': self.__select__() elif event.keysym == 'BackSpace': self.text = self.text[:-1] elif event.keysym in util.alphabet(): self.text += \ util.translate(event.keysym) else: return [ self.delete(id) for id in self.mvis ] self.mvis += [ self.create_text( ( int(self['width'] )/2 - 145, int(self['height'])/2), text = self.text, font = util.config.settings['Font'], anchor = 'w', fill = 'white' ) ]
def failed_pattern_go(line, pattern, verbose=0): global must_restart global failed_commands pat = re.compile(pattern) match = pat.search(line) if match: s = util.translate(match.group(1)) if s == "": return elif s == match.group(1): # the requirement it's also golang libpath format # (e.g: github.com/<project>/<repo> so transform into pkg name s = util.golang_name(s) try: must_restart = must_restart + buildreq.add_buildreq(s) except: if verbose > 0: print("Unknown golang pattern match: ", pattern, s, line)
def showAll(pnt=Base.Vector(0, 0, 0), dir=Base.Vector(0, 0, 1)): util.clear() parts = [partFromVectors([O, x(1000), xy(1000, 1000), y(1000)], O - z(thickness))] util.concat(parts, util.translate(chair(), x(0))) # util.concat(parts,util.translate(chair('sym'), x(1500))) # util.concat(parts,util.translate(chair('tri'), x(3000))) doc = FreeCAD.activeDocument() grp = doc.addObject("App::DocumentObjectGroup", "Workbench") print(parts) for p in parts: o = doc.addObject("Part::Feature", "Part") if(hasattr(p, 'delegate')): o.Shape = p.delegate else: o.Shape = p grp.addObject(o) pass
def __keypress__(self, event): # Handling for Enemies: if self.enemy: # When a field is focused: if self.locked: # Determine name of focused field: if self.position[1] == 1: lock_name = 'Name' elif self.position[1] == 2: lock_name = 'Health' elif self.position[1] == 3: lock_name = 'Attack' elif self.position[1] == 4: lock_name = 'Speed' elif self.position[1] == 5: lock_name = 'Range' # Assign Events to Field: TODO: REFACTOR OUT if event.keysym == 'Return': self.locked = False self.position[1] += 1 elif event.keysym == 'BackSpace': self.fields[lock_name] = self.fields[lock_name][:-1] elif event.keysym in util.alphabet(): self.fields[lock_name] += util.translate(event.keysym) else: return else: # When NOTHING is focused: if event.keysym in util.config.keys['Menu_Up']: self.position[1] -= 1 elif event.keysym in util.config.keys['Menu_Down']: self.position[1] += 1 elif event.keysym in util.config.keys['Menu_Right']: if self.position[1] == 0: self.enemy = False self.position.max = (1, 4) elif event.keysym in util.config.keys['Menu_Select']: if self.position[1] in range(1, 6): self.locked = True elif self.position[1] == 6: self.advance() return else: pass elif event.keysym in util.config.keys['Menu_Back']: self.master(self.old) else: # Handling for Pick-Up Items: # When a field is focused: if self.locked: # Determine name of focused field: if self.position[1] == 1: lock_name = 'Name' elif self.position[1] == 2: lock_name = 'Count' # Assign Events to Field: TODO: DOUBLE if event.keysym == 'Return': self.locked = False self.position[1] += 1 elif event.keysym == 'BackSpace': self.fields[lock_name] = self.fields[lock_name][:-1] elif event.keysym in util.alphabet(): self.fields[lock_name] += util.translate(event.keysym) else: return else: # When NOTHING is focused: if event.keysym in util.config.keys['Menu_Up']: self.position[1] -= 1 elif event.keysym in util.config.keys['Menu_Down']: self.position[1] += 1 elif event.keysym in util.config.keys['Menu_Left']: if self.position[1] == 0: self.enemy = True self.position.max = (1, 7) elif event.keysym in util.config.keys['Menu_Select']: if self.position[1] in range(1, 3): self.locked = True elif self.position[1] == 3: self.advance() return else: pass elif event.keysym in util.config.keys['Menu_Back']: self.master(self.old) self.draw()