def _inspect_adjacent(self, node): pos = Point(node.x, node.y) for neighbor in self._adjacency_list(pos): new_g = node.g + pos.diagnol_distance(neighbor) if neighbor.blocks_move: continue self._searched_nodes.add(neighbor) if new_g < neighbor.g: # this path is better if neighbor in self._open: # new path is better, take it out of open self._open.remove(neighbor) #self._open_set.discard(neighbor.coord) if neighbor.coord in self._closed_set: self._closed_set.add(neighbor.coord) if neighbor not in self._open and \ neighbor.coord not in self._closed_set: neighbor.g = new_g neighbor.h = self._heuristic(neighbor, self.target_node) neighbor.f = neighbor.g + neighbor.h neighbor.parent = node heapq.heappush(self._open, neighbor)
def watchOnce(self): if not Point.isStcokTime(): print('is not stock time, current time:' + str(dt.current_time())) return try: point = Point.getNow(self.code) except: return self.onNewPoint(point)
def compute(data, velocity=Directions.RIGHT, instructions=_instructions): origin = Point(0, 0) pv = PointVector(origin, velocity) for line in data.strip().splitlines(): instruction = line[0] arg = int(line[1:]) pv = instructions[instruction](arg, pv) return origin.manhattan_dist(pv.position)
def __init__(self): #TODO:Remove Path module Map.__init__(self) self.height = 800 self.length = 600 #self.pathList.append(Path(0, 300, 600, 300, 16)); self.pathPointList = [] self.pathPointList.append(Point(0, 400)) self.pathPointList.append(Point(600, 400)) self.pathSize = 16
def __init__(self, vertices: List[Point]) -> None: if not isinstance(vertices, list): raise TypeError("input vertices should be a list") if len(vertices) <= 2: raise IOError("Polygon should at least have 3 vertices.") self.vertices = vertices self.max_point = Point(-sys.maxsize, -sys.maxsize) self.min_point = Point(sys.maxsize, sys.maxsize) self.assign_limits()
def getPointList(self): ''' 成功返回list和None, 否则返回list和错误信息 ''' pointList = [] err = None raw, err = self.fetchRaw() raw = raw.strip() if err != None: return pointList, err try: data = ujson.loads(raw) data = data[0]['hq'] for dayData in data: p = Point() # 0 1 2 3 4 5 6 7 8 9 #日期,开盘,收盘,涨跌,涨幅,最低,最高,成交量,成交额,换手 p.code = self.code p.time = dayData[0] p.dayBegin = dayData[1] p.dayEnd = dayData[2] p.dayMin = dayData[5] p.dayMax = dayData[6] pointList.append(p) except Exception as ex: err = str(ex) return pointList, err
def test_direction_to(self): assert_that(Point(2, 2).direction_to(Point(2, 1)), is_(Directions.UP)) assert_that( Point(2, 2).direction_to(Point(3, 2)), is_(Directions.RIGHT)) assert_that( Point(2, 2).direction_to(Point(1, 2)), is_(Directions.LEFT)) assert_that( Point(2, 2).direction_to(Point(2, 3)), is_(Directions.DOWN))
def parseMoveKey(key): res = Point() if not key: return if key in 'KEY_DOWN, j': res.y += 1 elif key in 'KEY_UP, k': res.y -= 1 elif key in 'KEY_LEFT, h': res.x -= 1 elif key in 'KEY_RIGHT, l': res.x += 1 elif key in 'y': res.x -= 1 res.y -= 1 elif key in 'u': res.x += 1 res.y -= 1 elif key in 'b': res.x -= 1 res.y += 1 elif key in 'n': res.x += 1 res.y += 1 else: return return res
def __init__(self, chemin, vie, speed): self.vie = vie self.speed = speed #vitesse en pixel/update self.chemin = iter(chemin) position = next(self.chemin) #depart self.pos = Point(position.x, position.y) self.target = self.set_next_target() #trouver la cible
def __set_absolute_position(self): if self._parent_painter: self._absolute_position = self._parent_painter._absolute_position + self._relative_position if self._parent_painter._scroll: self._absolute_position -= self._parent_painter._scroll else: self._absolute_position = Point(0, 0, 0)
def scanOne(cls, etf, beforeDayNum=2): gevent.sleep(0.001) startDate, endDate = cls.getBeginEndDate(20) sh = StockHistory(etf.code.lower(), startDate, endDate) pointList, err = sh.getPointList() if err != None: cls.logError("get etf history failed:" + str(err)) return index = 0 - beforeDayNum pointList = pointList[index:] length = len(pointList) #判断价格是否连续下跌 isStillRise = True for i in range(length - 1): if pointList[i].dayEnd <= pointList[i + 1].dayEnd: isStillRise = False if isStillRise == False: return #判断是否连续下跌 for point in pointList: if point.dayBegin <= point.dayEnd: return now = Point.getNow(etf.code) #大于30块的不要 if now.now >= 30: return msg = NotifyTpl.genETFRiseTpl('关注信息', etf.name, etf.code, length, now.now) notify.asyncSendMsg(msg)
def flip(image): new_features = { Point(p.x, image.data.rect.height - p.y): v for p, v in image.data.features.items() } return replace(image, data=replace(image.data, features=new_features))
def _(line_1: Line, line_2: Line) -> Optional[Point]: intersection = lib.geometry.cross3(line_1.as_tuple(), line_2.as_tuple()) if lib.math_utils.are_almost_equal(intersection[2], 0): return None return Point(intersection[0] / intersection[2], intersection[1] / intersection[2])
def scan(cls, stock, beforeDayNum=10): gevent.sleep(0.001) #如果是ST类型的股票,不分析 if 'ST' in stock.name or 'st' in stock.name: return startDate, endDate = cls.getBeginEndDate(35) print(startDate, endDate) sh = StockHistory(code=stock.code, startDate=startDate, endDate=endDate) pointList, err = sh.getPointList() if err != None: cls.logError("code:%s, name:%s, get history failed:%s" % (stock.code, stock.name, err)) return index = 0 - beforeDayNum pointList = pointList[index:] for point in pointList: if point.dayBegin >= point.dayEnd: return #判断价格是否连续上涨 isStillRose = True length = len(pointList) for i in range(length - 1): if pointList[i].dayEnd >= pointList[i + 1].dayEnd: isStillRose = False if isStillRose == False: return now = Point.getNow(stock.code) msg = NotifyTpl.genStillRoseNotify('关注信号', stock.name, stock.code, length, now.now) notify.asyncSendMsg(msg)
def checkOnce(cls): gevent.sleep(0.001) f = open('./data/his_buy_profit.json', 'r') content = f.read() f.close() data = demjson.decode(content) for code, buyProfitList in data.items(): buyProfitList.sort() print(code, buyProfitList) point = Point.getNow(code) print(point) isLessThanHis = False comparePrice = 0 for price in buyProfitList: if point.now <= price: isLessThanHis = True comparePrice = price break print(isLessThanHis, point.now) if not isLessThanHis: continue print('allow send:', cls.isAllowSend(code)) if not cls.isAllowSend(code): return msg = NotifyTpl.genHisBuyProfitNotify('买入信号', point.name, code, point.now, comparePrice) print('msg:', msg) notify.defaultSendDDMsg(msg) cls.markSend(code)
def test_extended_neighbors(self): assert_that( Point(2, 2).extended_neighbors, is_([ Point(1, 1), Point(2, 1), Point(3, 1), Point(1, 2), Point(3, 2), Point(1, 3), Point(2, 3), Point(3, 3) ]))
def get_final_image(full_map, height, width): chunks_size = full_map[Point(0, 0)].data.rect.width - 1 image_parts = {} for y in range(height): for x in range(width): img = full_map[Point(x, y)] for i_y in range(1, img.data.rect.height): for i_x in range(1, img.data.rect.width): writing_at = Point(x * chunks_size + i_x - 1, y * chunks_size + i_y - 1) # print(writing_at) image_parts[writing_at] = img.data[Point(i_x, i_y)] final_image = Image( 0, tuple(), Map(image_parts, Rectangle.by_size(chunks_size * width, chunks_size * height))) return final_image
def check_slope(field, move_x=3, move_y=1): trees = 0 x = 0 for y in range(move_y, field.rect.height, move_y): x = (x + move_x) % field.rect.width if field.features.get(Point(x, y)) == TREE: trees += 1 return trees
def __str__(self): out = f'Map <{self.rect}>\n' lines = [] for y in range(self.rect.top, self.rect.bottom + 1): lines.append(''.join( self.features.get(Point(x, y), ' ') for x in range(self.rect.left, self.rect.right + 1))) return out + '\n'.join(lines)
def rot(image): new_features = { p + Point(image.data.rect.width - p.x - p.y, image.data.rect.height - p.y - image.data.rect.width + p.x): v for p, v in image.data.features.items() } return replace(image, data=replace(image.data, features=new_features))
def from_input(cls, data: str, features: Container[str]) -> 'Map': points = {} lines = data.splitlines() for y, line in enumerate(lines): for x, content in enumerate(line): if not features or content in features: points[Point(x, y)] = content return cls(points, Rectangle.by_size(len(lines[0]), len(lines)))
def safeSendDDMsg(ddrotUrl='', msg='', timeout=10): if not Point.isStcokTime(): return code = output = None try: code, output = sendDDMsg(ddrotUrl, msg, timeout) except Exception as ex: print('safeSendDDMsg exception:' + str(ex)) pass return code, output
def remove_serpents(version, serpent): rough = version.data.features.copy() for y in range(version.data.rect.height - serpent.rect.height - 1): for x in range(version.data.rect.width - serpent.rect.width - 1): offset = Point(x, y) if all(rough[offset + p] == '#' for p in serpent.features.keys()): for p in serpent.features.keys(): rough[offset + p] = '.' return rough
async def handle(self): try: code = self.param('code') remote = self.remoteAddr() self.logInfo(f'code:{code}, remote:{remote}') now = Point.getNow(code) return now.toString() except Exception as ex: return str(ex)
def start_map_from_sides(closest_corners): full_map = {} size = defaultdict(lambda: 0) for edge, direction in zip(closest_corners, [Directions.RIGHT, Directions.DOWN]): current = Point(0, 0) for img in edge: full_map[current] = img current += direction size[direction] += 1 width = size[Directions.RIGHT] height = size[Directions.DOWN] return full_map, height, width
def arrange_with_transformations(full_map, height, width): for y in range(height - 1): for x in range(width - 1): current = Point(x, y) image = full_map[current] for current_version in all_transforms(image): sync_with = { Directions.DOWN: full_map[current + Directions.DOWN], Directions.RIGHT: full_map[current + Directions.RIGHT], } result = {} for direction, other_image in sync_with.items(): border_to_match = ''.join( reversed(current_version.get_border(direction))) for other_version in all_transforms(other_image): if other_version.get_border( direction.opposite) == border_to_match: result[direction] = other_version break if len(result) == len(sync_with): full_map[current] = current_version for direction, other_version in result.items(): full_map[current + direction] = other_version last = Point(width - 1, height - 1) image = full_map[last] for version in all_transforms(image): directions = [Directions.UP, Directions.LEFT] matching = 0 for direction in [Directions.UP, Directions.LEFT]: border_to_match = ''.join(reversed(version.get_border(direction))) if full_map[last + direction].get_border( direction.opposite) == border_to_match: matching += 1 if matching == len(directions): full_map[last] = image break
def __init__(self, center, size, spacing, point_radius=.01): super().__init__() self.center = center self.size = size if type(size) == tuple else (size, size) self.spacing = spacing if type(spacing) == tuple else (spacing, spacing) self.objects = [ Point( i * self.spacing[0] - self.spacing[0] * (self.size[0] - 1) / 2 + self.center[0], j * self.spacing[1] - self.spacing[1] * (self.size[1] - 1) / 2 + self.center[1]) for i in range(self.size[0]) for j in range(self.size[1]) ] self.artists = [Circle(point, point_radius) for point in self.objects]
def fill_map(full_map, height, width, pairs): placed = set(full_map.values()) for y in range(1, height): for x in range(1, width): current = Point(x, y) relatives = [ full_map[current + Directions.LEFT], full_map[current + Directions.UP] ] for image, matching in pairs.items(): if image not in placed and all(r in matching for r in relatives): full_map[current] = image placed.add(image) break
def generate_random_points(num_points: int, points_range: Range) -> List[Point]: import random # seed random number generator generate random numbers between 0-1 random.seed(1) values = [] for _ in range(num_points): values.append(points_range.lo + random.random() * (points_range.hi - points_range.lo)) points = set() while len(points) < num_points: x = random.choice(values) y = random.choice(values) points.add(Point(x, y)) return list(points)
def scanOnce(cls, beforeDayNum, concurrentNum): cls.logInfo('ready scan') if not Point.isStcokTime(): return begin = time.time() stockList = StockList.getAllStock() index = 0 for stock in stockList: cls.safeAnaOneStock(stock, beforeDayNum) index = index + 1 cls.logInfo("name:%s,index:%s" % (stock.name, index)) end = time.time() cost = end - begin cls.logInfo('scan once finish, stock num:' + str(len(stockList)) + ' cost:' + str(int(cost)) + ' seconds')
def scanOnce(cls, beforeDayNum=10, concurrentNum=multiprocessing.cpu_count()): #for test if not Point.isStcokTime(): return begin = time.time() concurrentPool = pool.Pool(concurrentNum) stockList = StockList.getAllStock() index = 0 for stock in stockList: concurrentPool.spawn(cls.scan, stock, beforeDayNum) index = index + 1 cls.logInfo("name:%s,index:%s" % (stock.name, index)) concurrentPool.join() end = time.time() cost = end - begin cls.logInfo('scan once finish, stock num:' + str(len(stockList)) + ' cost:' + str(int(cost)) + ' seconds')
def test(cls): startDate, endDate = cls.getBeginEndDate(20) print(startDate, endDate) sh = StockHistory(code='sz002078', startDate=startDate, endDate=endDate) pointList, err = sh.getPointList() if err != None: print(err) return for p in pointList: print(p.dayMin, p.time) now = Point.getNow('sz002078') print('now:', now.now) isLatestMin = True for point in pointList: #按照日期升序2020-07-13 ~ 2020-07-14 #for test #print('code:', point.code, 'time:', point.time, 'dayBegin:', point.dayBegin, 'dayEnd:', point.dayEnd, 'dayMax:', point.dayMax, 'dayMin:', point.dayMin) if float(now.now) >= float(point.dayMin): isLatestMin = False break print('isLatestMin:', isLatestMin)
class Painter(object): # flags # scroll_direction NORTH = 1 SOUTH = 2 EAST = 4 WEST = 8 SCROLL_SPEED = 1 font = None def __init__(self, parent_painter, size = Point(0, 0), relative_position = Point(0, 0, 0), surface = None, scroll = None): if parent_painter and size == Point(0, 0): size = parent_painter.get_size() if surface is None: surface = pygame.Surface(size.to_vector2()).convert_alpha() self._scale = 16 if parent_painter: self._scale = parent_painter._scale self._parent_painter = parent_painter self._surface = surface self._scaled_surfaces = {} self._scaled_surfaces[self._scale] = self._surface self._size = size self._scroll = scroll self._relative_position = relative_position self.__set_absolute_position() self.__set_scaled_position() self._rotation = None self._index = dict() self.set_scale(self._scale) self.set_relative_position(relative_position) self._scroll_direction = 0 self._dirty = True if self._parent_painter: self._parent_painter.append(self) def set_size(self, size): self._size = Point(size) def get_size(self): return self._size def set_surface(self, surface): self._surface = surface self._scaled_surfaces = dict() self.set_scale(self._scale) def set_scale(self, scale): self._relative_position /= self._scale self._scale = scale if self._relative_position: self.set_relative_position(self._relative_position * self._scale) if self._scale not in self._scaled_surfaces: self._scaled_surfaces[self._scale] = pygame.transform.scale(self._surface, (self._surface.get_width() * self._scale / 16, self._surface.get_height() * self._scale / 16)) self.__set_scaled_position() self.__bound_check_scroll() self.__set_viewable_surface() self.set_dirty() for z in sorted(self._index.iterkeys()): for y in sorted(self._index[z].iterkeys()): for x in sorted(self._index[z][y].iterkeys()): for painter in self._index[z][y][x]: painter.set_scale(scale) def set_relative_position(self, relative_position): self._relative_position = relative_position self.__set_absolute_position() self.__set_scaled_position() self.__set_viewable_surface() def __set_scaled_position(self): # if self._parent_painter and self._scaled_position: # self._parent_painter.remove(self) self._scaled_position = Point( self._relative_position.x / self._scale, self._relative_position.y / self._scale, self._relative_position.z / self._scale ) # if self._parent_painter: # self._parent_painter.append(self) def __set_absolute_position(self): if self._parent_painter: self._absolute_position = self._parent_painter._absolute_position + self._relative_position if self._parent_painter._scroll: self._absolute_position -= self._parent_painter._scroll else: self._absolute_position = Point(0, 0, 0) def __set_viewable_surface(self): if self._scale in self._scaled_surfaces: self.__viewable_surface = self._scaled_surfaces[self._scale] else: self.__viewable_surface = self._surface.copy() self.__set_absolute_position() if self._rotation: self.__viewable_surface = pygame.transform.rotate(self.__viewable_surface, self._rotation * 180 / math.pi % 360) if self._scroll: viewable_area = pygame.Rect(self._scroll.to_vector2(), self.get_size().to_vector2()).clamp(self.__viewable_surface.get_rect()).clip(self.__viewable_surface.get_rect()) self.__viewable_surface = self.__viewable_surface.subsurface(viewable_area) def append(self, painter): if painter._scaled_position.x not in self._index: self._index[painter._scaled_position.x] = dict() if painter._scaled_position.y not in self._index[painter._scaled_position.x]: self._index[painter._scaled_position.x][painter._scaled_position.y] = dict() if painter._scaled_position.z not in self._index[painter._scaled_position.x][painter._scaled_position.y]: self._index[painter._scaled_position.x][painter._scaled_position.y][painter._scaled_position.z] = list() self._index[painter._scaled_position.x][painter._scaled_position.y][painter._scaled_position.z].append(painter) def remove(self, painter): self._index[painter._scaled_position.x][painter._scaled_position.y][painter._scaled_position.z].remove(painter) def update(self, elapsed): self._dirty = False self.scroll(elapsed) self.__set_viewable_surface() def paint(self, elapsed): if self._dirty: self.update(elapsed) GameState.main_surface.blit(self.__viewable_surface, self._absolute_position.to_vector2()) for z in sorted(self._index.iterkeys()): for y in sorted(self._index[z].iterkeys()): for x in sorted(self._index[z][y].iterkeys()): for painter in self._index[z][y][x]: painter.paint(elapsed) def set_size(self, size): self._size = size def get_size(self): return self._size def set_scroll_direction(self, direction): if direction: self._scroll_direction |= direction else: self._scroll_direction = 0 self.set_dirty() # is this really necessary? def scroll(self, elapsed): if self._scroll_direction: distance = elapsed * Painter.SCROLL_SPEED if self._scroll_direction & Painter.NORTH: self._scroll_north(distance) elif self._scroll_direction & Painter.SOUTH: self._scroll_south(distance) if self._scroll_direction & Painter.EAST: self._scroll_east(distance) elif self._scroll_direction & Painter.WEST: self._scroll_west(distance) self.__bound_check_scroll() self.set_dirty() def _scroll_north(self, distance): self._scroll -= (0, distance) def _scroll_south(self, distance): self._scroll += (0, distance) def _scroll_east(self, distance): self._scroll -= (distance, 0) def _scroll_west(self, distance): self._scroll += (distance, 0) def __bound_check_scroll(self): if self._scroll: limit = self._scaled_surfaces[self._scale].get_size() - self.get_size() limit.constrain(Point(0, 0), Point(*self._scaled_surfaces[self._scale].get_size())) self._scroll.constrain(Point(0, 0), limit) def set_dirty(self, dirty = True): self._dirty = dirty
def _heuristic(self, node_a, node_b): p_a = Point(node_a.x, node_a.y) return p_a.diagnol_distance(node_b)