• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python position.Position类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中position.Position的典型用法代码示例。如果您正苦于以下问题:Python Position类的具体用法?Python Position怎么用?Python Position使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Position类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: expand_frontier

	def expand_frontier(self, state):
		for row in (-1, 0, 1):
			for col in (-1, 0, 1):
				# Only allow adjacent non-diagonal moves
				#if row != 0 and col != 0:
				#	continue

				# Get the new position
				position = Position(state.row() + row, state.column() + col)

				# Rule out invalid positions
				if position.row() < 0 or position.column() < 0 or \
				   position.row() >= self.environment.height or position.column() >= self.environment.width:
					return

				p = position.as_tuple()

				# If not an obstacle and not explored, then add to frontier
				if p not in self.environment.obstacles and p not in self.explored:
					self.f += 1

					# Create the new state
					new_state = State(position, state.target, state.cost + 1, state)

					# Update state path cost
					new_state.path_cost = new_state.cost + self.heuristic(new_state)
					

					# Add to frontier
					self.frontier.add(new_state)
开发者ID:AlejoAsd,项目名称:AStar,代码行数:30,代码来源:actor.py


示例2: __init__

 def __init__(self):
     Position.__init__(self)
     self.rect = None
     self.image = None
     self.name = None
     self.type = None
     self.has_dialog = False
开发者ID:joaopgom,项目名称:rpg-v2,代码行数:7,代码来源:map.py


示例3: openPosition

    def openPosition(self, order, bar, market = False):
        position = 0
        if order.instrument != "" and order.instrument != bar[11]:
            print "bar of other instrument!" #exception here
            raise NotImplementedError

        if market:
            if order.orderType == -1:
                order.price = bar[4]
            else:
                order.price = bar[9]
            position = Position(order, bar[0], self.slippage, self.randomizeSlippage, self.point, stat = [])
            if self.getStat:
                position.stat = []
                position.stat.append(self.strategy.onGetStatOnPositionOpen(position, bar))
        else:
            position = Position(order, bar[0], stat = [])
            if self.getStat:
                position.stat = []
                position.stat.append(self.strategy.onGetStatOnPositionOpen(position, bar))


        self.positions.append(position)
        self.orders.remove(position.order)
        self.strategy.onOrderExecution(position.order)
开发者ID:forregg,项目名称:cbTester,代码行数:25,代码来源:tester.py


示例4: TestLongGBPUSDPosition

class TestLongGBPUSDPosition(unittest.TestCase):
    def setUp(self):
        getcontext.prec = 2
        side = "LONG"
        market = "GBP/USD"
        units = Decimal(str(2000))
        exposure = Decimal("2000.00")
        avg_price = Decimal("1.51819")
        cur_price = Decimal("1.51770")
        self.position = Position(
            side, market, units, exposure,
            avg_price, cur_price
        )

    def test_calculate_pips(self):
        pos_pips = self.position.calculate_pips()
        self.assertEqual(pos_pips, Decimal("-0.00049"))

    def test_calculate_profit_base(self):
        profit_base = self.position.calculate_profit_base(self.position.exposure)
        self.assertEqual(profit_base, Decimal("-0.64571"))

    def test_calculate_profit_perc(self):
        profit_perc = self.position.calculate_profit_perc(self.position.exposure)
        self.assertEqual(profit_perc, Decimal("-0.03229"))
开发者ID:flight90,项目名称:qsforex,代码行数:25,代码来源:position_test.py


示例5: funcVisit

 def funcVisit(self, x, y):
     pos = Position(x, y)
     if pos.x < 0:
         pos.x = 0
     if pos.y < 0:
         pos.y = 0
     self.map[pos.x][pos.y].visible = True
     self.map[pos.x][pos.y].discovered = True
开发者ID:kunwon1,项目名称:UGUIR,代码行数:8,代码来源:gamemap.py


示例6: test_move_info

 def test_move_info(self):
     """Tests move info generation."""
     pos = Position()
     e4 = pos.get_move_info(Move.from_uci('e2e4'))
     self.assertEqual(e4.san, 'e4')
     self.assertFalse(e4.is_check)
     self.assertFalse(e4.is_checkmate)
     self.assertFalse(e4.is_castle)
开发者ID:arthurfait,项目名称:kivy-chess,代码行数:8,代码来源:old_test_position.py


示例7: generate_long_algebraic_moves

 def generate_long_algebraic_moves(self):
   position = Position()
   for move in self.moves:
     try:
       long_move = "%s%s%s" % position.move(move)
       if len(long_move) > 0:
         yield long_move
     except Exception, err:
       raise BaseException("Could not process move %s (%s)" % (move, err))
开发者ID:pickhardt,项目名称:chessbox,代码行数:9,代码来源:game.py


示例8: TestRoundTripXOPosition

class TestRoundTripXOPosition(unittest.TestCase):
    """
    Trade a round-trip trade in Exxon-MObil where the initial
    trade is a buy/long of 100 shares of XOM, at a price of
    $74.78, with $1.00 commission.
    """
    def setUp(self):
        """
        Set up the Position object that wil store the PnL.
        """
        self.position = Position('BOT', 'XOM', Decimal('100'), 
                                Decimal('74.78'), Decimal('1.00'), 
                                Decimal('74.78'), Decimal('74.78'))

    def test_calculate_round_trip(self):
            
        """
        After the subsequent purchase, carry outtwo more buys/longs
        and then close the position out with two additional sells/shorts.

        The following prices have been tested against those calculated
        via Interactive Brokers' Trader Workstation (TWS).
        """

        # set the data in the object
        self.position.transact_shares('BOT', Decimal('100'), Decimal('74.63'), Decimal('1.00'))

        self.position.transact_shares('BOT', Decimal('250'), Decimal('74.620'), Decimal('1.25'))
        
        self.position.transact_shares('SLD', Decimal('200'), Decimal('74.58'), Decimal('1.00'))

        self.position.transact_shares('SLD', Decimal('250'), Decimal('75.26'), Decimal('1.25'))

        self.position.update_market_value(Decimal('77.75'), Decimal('77.77'))

        # start testing the values inside the object
        # the assertEqual method is derived by the unittest.TestCase from which the class derive from 
        self.assertEqual(self.position.action, 'BOT')
        self.assertEqual(self.position.ticker, 'XOM')
        self.assertEqual(self.position.quantity, Decimal('0'))

        self.assertEqual(self.position.buys, Decimal('450'))
        self.assertEqual(self.position.sells, Decimal('450'))
        self.assertEqual(self.position.net, Decimal('0'))
        self.assertEqual(self.position.avg_bot, Decimal('74.65778'))
        self.assertEqual(self.position.avg_sld, Decimal('74.95778'))
        self.assertEqual(self.position.total_bot, Decimal('33596.00'))
        self.assertEqual(self.position.total_sld, Decimal('33731.00'))
        self.assertEqual(self.position.net_total, Decimal('135.00'))
        self.assertEqual(self.position.total_commission, Decimal('5.50'))
        self.assertEqual(self.position.net_incl_comm, Decimal('129.50'))
            
        self.assertEqual(self.position.avg_price, Decimal('74.665'))
        self.assertEqual(self.position.cost_basis, Decimal('0.00'))
        self.assertEqual(self.position.market_value, Decimal('0.00'))
        self.assertEqual(self.position.unrealised_pnl, Decimal('0.00'))
        self.assertEqual(self.position.realised_pnl, Decimal('129.50'))
开发者ID:LoShan17,项目名称:TradingInfrastructure,代码行数:57,代码来源:position_test.py


示例9: move

 def move(self, steps: int) -> 'MegaCar':
     """
     Move car "step" amount of places.
     """
     if self.horizontal:
         return Car.new(self.start + Position.new(steps, 0), self.horizontal,
                        self.length)
     else:
         return Car.new(self.start + Position.new(0, steps), self.horizontal,
                        self.length)
开发者ID:kasperpeulen,项目名称:rushhour,代码行数:10,代码来源:board.py


示例10: __repr__

    def __repr__(self):
        result = "Account %s\n" % (self.name)

        result += "  %s\n" % (Position.format(Account.CASH, None, None, self.cash),)

        for position in self.positions.values():
            result += "  %s\n" % position

        result += "================"
        result += "  %s\n" % (Position.format(None, None, None, account.get_value()),)
        return result
开发者ID:helvetix,项目名称:Experimental-Tools,代码行数:11,代码来源:account.py


示例11: setUp

 def setUp(self):
     p = Position()
     self.moves = p.get_legal_moves()
     m1 = Move.from_uci('e2e4')
     m2 = Move.from_uci('b1c3')
     self.san = SanNotation(p, m1)
     self.san_dup = SanNotation(p, m1)
     self.san_other = SanNotation(p, m2)
     self.position = p
     self.m1 = m1
     self.m2 = m2
开发者ID:arthurfait,项目名称:kivy-chess,代码行数:11,代码来源:test_notation.py


示例12: TestPosition

class TestPosition(unittest.TestCase):
    
    def setUp(self):
        self.pos = Position()
        self.pos_dup = Position()
        self.pos_other = Position()
        self.pos_other.make_move(Move.from_uci('e2e4'))

    def test___delitem__(self):
        del self.pos['a1']
        self.assertIs(None, self.pos['a1'])

    def test___eq__(self):
        self.assertEqual(True, self.pos == self.pos_dup)
        self.assertEqual(False, self.pos == self.pos_other)

    def test___getitem__(self):
        self.assertEqual(True, self.pos['e1'] == 'K')

    def test___hash__(self):
        self.assertEqual(True, hash(self.pos) == hash(self.pos_dup))
        self.assertEqual(False, hash(self.pos) != hash(self.pos_other))

    def test___ne__(self):
        self.assertEqual(False, self.pos != self.pos_dup)
        self.assertEqual(True, self.pos != self.pos_other)

    def test___repr__(self):
        self.assertEqual("Position('%s')" % Fen(), repr(self.pos))

    def test___setitem__(self):
        self.pos['a1'] = 'K'
        self.assertEqual('K', self.pos['a1'])

    def test___str__(self):
        self.assertEqual(str(Fen()), str(self.pos))
        self.assertEqual(False, str(self.pos) == str(self.pos_other))

    def test_copy(self):
        copy = self.pos.copy()
        self.assertEqual(copy, self.pos)

    def test_is_check(self):
        self.assertEqual(False, self.pos.is_check())

    def test_is_checkmate(self):
        self.assertEqual(False, self.pos.is_checkmate())

    def test_is_game_over(self):
        self.assertEqual(False, self.pos.is_game_over())

    def test_is_insufficient_material(self):
        self.assertEqual(False, self.pos.is_insufficient_material())

    def test_is_king_attacked(self):
        self.assertEqual(False, self.pos.is_king_attacked(WHITE))

    def test_is_stalemate(self):
        self.assertEqual(False, self.pos.is_stalemate())
开发者ID:arthurfait,项目名称:kivy-chess,代码行数:59,代码来源:test_position.py


示例13: cmdBreak

def cmdBreak(invoker):
    preprocess = not invoker.hasOption("*")
    invoker.checkUnsupportedOptions()

    arguments = invoker.getArguments().strip()
    runtime = invoker.getRuntime()
    position = runtime.getPosition(runtime.getCurrentFrame())

    if not arguments:
        if not position:
            raise CommandError, "%s: no current position" % invoker.getName()
        id = invoker.getSession().addBreakpointAtPosition(position)
        at = position.getShortDescription()
    else:
        words = arguments.split()
        linenr_required = False

        if words[0][0] == '#':
            linenr_required = True
            linenr_string = words[1]
            try:
                scriptindex = int(words[0][1:])
                script = invoker.getSession().getScriptByIndex(scriptindex)
                if not script: 
                    raise ValueError
            except ValueError:
                raise CommandError, "%s: invalid script index: %s" % (invoker.getName(), words[0][1:])
        else:
            linenr_string = words[0]
            script = False

        try:
            linenr = int(linenr_string)
            if not script:
                if not position: 
                    raise CommandError, "%s: no current script" % invoker.getName()
                script = position.getScript()
            position = Position(script, linenr)
            id = invoker.getSession().addBreakpointAtPosition(position)
            at = position.getShortDescription()
        except ValueError:
            if linenr_required:
                raise CommandError, "%s: line number required" % invoker.getName()
            try:
                result = runtime.eval(words[0], True, preprocess)
            except KeyboardInterrupt: 
                return []
            if not result.isObject() or not result.getValue().isFunction(): 
                raise CommandError, "%s: not a function: %s" % (invoker.getName(), result)
            id = invoker.getSession().addBreakpointAtFunction(result.getValue())
            at = str(result)

    return ["Breakpoint %d at %s." % (id, at)]
开发者ID:prestocore,项目名称:browser,代码行数:53,代码来源:cmd-breakpoint.py


示例14: simulation

 def simulation(self):
     """This function will perform the simulation process with several trials."""
     for pos in self.positions:
         p = Position(pos)
         cumu_ret = np.zeros(self.num_trials)
         daily_ret = np.zeros(self.num_trials)
         for trial in range(self.num_trials):
             #Get a daily return value
             cumu_ret[trial] = p.invest()
             #convert return value to return ratio
             daily_ret[trial] = (cumu_ret[trial] / 1000.0) - 1
         self.trials.append(daily_ret)
开发者ID:whirlkick,项目名称:assignment8,代码行数:12,代码来源:investment_simulation.py


示例15: __init__

 def __init__(self, name):
     Position.__init__(self)
     self.name = name
     load_creature(self.name)
     self.hp = CREATURES_LOADED[self.name]['hp']
     self.mp = CREATURES_LOADED[self.name]['mp']
     self.level = CREATURES_LOADED[self.name]['level']
     self.attack = CREATURES_LOADED[self.name]['attack']
     self.attack_m = CREATURES_LOADED[self.name]['attack_m']
     self._class = CREATURES_LOADED[self.name]['_class']
     self._def = CREATURES_LOADED[self.name]['_def']
     self.def_m = CREATURES_LOADED[self.name]['def_m']
     self.selfie = None
开发者ID:joaopgom,项目名称:rpg-v2,代码行数:13,代码来源:player.py


示例16: TestRoundTripPGPosition

class TestRoundTripPGPosition(unittest.TestCase):
    """
    Test a round-trip trade in Proctor & Gamble where the initial
    trade is a sell/short of 100 shares of PG, at a price of $77.69, with $1.00 commission.
    """

    def setUp(self):
        self.position = Position('SLD', 'PG', Decimal('100'), 
                                Decimal('77.69'), Decimal('1.00'), 
                                Decimal('77.68'), Decimal('77.70'))

    def test_calculate_round_trip(self):
        """
        After the subsequent sale, carry out two more sells/shorts
        and then close the position out with two additional buys/longs.

        The following prices have been tested against those calculated
        via Interactive Brokers' Trader Workstation (TWS).
        """

        self.position.transact_shares('SLD', Decimal('100'), Decimal('77.68'), Decimal('1.00'))

        self.position.transact_shares('SLD', Decimal('50'), Decimal('77.70'), Decimal('1.00'))

        self.position.transact_shares('BOT', Decimal('100'), Decimal('77.77'), Decimal('1.00'))

        self.position.transact_shares('BOT', Decimal('150'), Decimal('77.73'), Decimal('1.00'))

        self.position.update_market_value(Decimal('77.72'), Decimal('77.72'))

        self.assertEqual(self.position.action, 'SLD')
        self.assertEqual(self.position.ticker, 'PG')
        self.assertEqual(self.position.quantity, Decimal('0'))

        self.assertEqual(self.position.buys, Decimal('250'))
        self.assertEqual(self.position.sells, Decimal('250'))
        self.assertEqual(self.position.net, Decimal('0'))
        self.assertEqual(self.position.avg_bot, Decimal('77.746'))
        self.assertEqual(self.position.avg_sld, Decimal('77.688'))
        self.assertEqual(self.position.total_bot, Decimal('19436.50'))
        self.assertEqual(self.position.total_sld, Decimal('19422.00'))
        self.assertEqual(self.position.net_total, Decimal('-14.50'))
        self.assertEqual(self.position.total_commission, Decimal('5.00'))
        self.assertEqual(self.position.net_incl_comm, Decimal('-19.50'))
            
        self.assertEqual(self.position.avg_price, Decimal('77.67600'))
        self.assertEqual(self.position.cost_basis, Decimal('0.00'))
        self.assertEqual(self.position.market_value, Decimal('0.00'))
        self.assertEqual(self.position.unrealised_pnl, Decimal('0.00'))
        self.assertEqual(self.position.realised_pnl, Decimal('-19.50'))
开发者ID:LoShan17,项目名称:TradingInfrastructure,代码行数:50,代码来源:position_test.py


示例17: _compute_path

    def _compute_path(self, airplane, timelimit):
        
        #print "looking for a path from " + str(start) + " to " + str(dest) + ", starting at " + str(p)

        begin_computation = time.time()

        start = Position(airplane)
        start.time = self._arena.clock
        plan = [ start ]
        
        # aim for approach position, one step in front of airport
        if isinstance(airplane.dest, Airport):
            tmp = Position(airplane.dest)
            tmp.dir = tmp.reverseDirection()
            approach = tmp.step(0, 1)
            approach.dir = airplane.dest.dir # turn around
        else:
            approach = Position(airplane.dest)

        approach.dir_tolerance = 90 # allow max. 90 degree derivation from target direction
        
        # enter recursion
        if not self._step_recursive(airplane, plan, start, approach, timelimit):
            if time.time() > timelimit:
                print "Path of " + str(airplane) + " from " + str(start) + " to " + str(airplane.dest) + ": COMPUTATION TIMEOUT (comp.time=" + \
                str(int((time.time()-begin_computation) * 1000000)/1000.0) + "ms)"
            else:
                print "Airplane " + str(airplane) + " will delay its take-off due to ongoing traffic"
            return False
            
        # append destination itself
        d = Position(airplane.dest)
        d.time = plan[-1].time + 1
        plan.append( d )
        
        self._compute_commands(plan, airplane)
            
        print "Path of " + str(airplane) + " from " + str(start) + " to " + str(airplane.dest) + " (" + str(len(plan)) + " steps, comp.time=" + \
        str(int((time.time()-begin_computation) * 100000)/100.0) + "ms): ",
        print string.join(map(str, plan), '; ')

        # add schedule to database
        for s in plan:
            if s.time < self._arena.clock:
                raise Exception("can't schedule for past time " + str(s.time) + ". current time: " + str(self._arena.clock))
            if not s.time in self._schedules:
                self._schedules[s.time] = {}
            self._schedules[s.time][airplane] = s
        
        return True
开发者ID:basman,项目名称:atc_bot,代码行数:50,代码来源:scheduler.py


示例18: set_static

 def set_static(self, pix_pos=None, x_shift=None, y_shift=None, x_offset=0, y_offset=0,
                z=1, scale=1.0):
     if pix_pos is None:
         pix_pos = Position()
     else:
         pix_pos = Position(pos=pix_pos)
     if x_shift is None or y_shift is None:
         self.states['static']['pix'].append(self.sheet)
     else:
         self.states['static']['pix'].append(self.sheet.copy(pix_pos.x(), pix_pos.y(), x_shift, y_shift))
     self.pix = self.parent.m_scene.addPixmap(self.states['static']['pix'][0])
     self.pix.setPos(self.pos.x(), self.pos.y())
     self.pix.setOffset(x_offset, y_offset)
     self.pix.setZValue(z)
     self.pix.setScale(scale)
开发者ID:mttchpmn07,项目名称:game_platform,代码行数:15,代码来源:sprite.py


示例19: __init__

 def __init__(self, view=None, position=None):
     Position.__init__(self)
     gobject.GObject.__init__(self)
     
     self.view = view    # associated BoardView
     self.game = None
     self.node = None    # the currently active game node
     
     for i in range(64):
         self.squares.append("")
     
     if position:
         self.set_position(position)
     else:
         self.setup_starting_pieces()
开发者ID:btrent,项目名称:chessmemory,代码行数:15,代码来源:board.py


示例20: _try_letters_at_position

 def _try_letters_at_position(self, board, letters_at_position):
   '''Adds the letters to the board at the given position. Returns False if a
   non-word is created by any letter.'''
   starting_pos = letters_at_position.position_with_direction.position.copy()
   direction = letters_at_position.position_with_direction.direction
   letters = letters_at_position.letters
   try:
     board.add_letters(letters, starting_pos, direction)
   except OutOfBoundsException:
     return False
   # Check that there is a word at the original position/direction
   if not self.is_word(board.get_word(starting_pos, direction)):
     # We didn't make a real word
     return False
   # We made a real word, now check to make sure we didn't create any
   # non-words in the other direction.
   other_direction = Position.get_other_direction(direction)
   moving_position = starting_pos.copy()
   for _ in range(len(letters)):
     generated_word = board.get_word(moving_position, other_direction)
     moving_position.add_in_direction(1, direction)  # for next time
     if len(generated_word) < 2:
       # This one isn't a word- it's just a letter. We're fine
       continue
     if not self.is_word(generated_word):
       # We accidentally made a non word!
       return False
   # We made a word, and didn't make any non-words in the other direction!
   return True
开发者ID:topher200,项目名称:scrabble-bot,代码行数:29,代码来源:game.py



注:本文中的position.Position类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.PositionEnteredManager类代码示例发布时间:2022-05-25
下一篇:
Python portpicker.pick_unused_port函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap