def onMotion(self, evt): old_offset = self.offset_pos #fix for windows focus policy ( after treeCtrl grabs focus it wont let it back ) self.SetFocus() if not self.moving: return #if not self.moving_proved: # self.pushMotionEvent(evt) # return curPos = evt.GetPosition() dx,dy = util.div(util.sub(self.prevPos, curPos), float(self.cell_size)) if dx != 0 or dy != 0: x,y=self.offset_pos x+=dx y+=dy self.offset_pos=(x,y) #self.Refresh() self.prevPos = curPos self.shift(util.mul(util.sub(old_offset, self.offset_pos), self.cell_size)) #self.update() self.Refresh() self.Update()
def _callback(self, **data): cb = self.template.callback if not cb: return callback_url = sub(cb.get("url"), **data) try: getattr(requests, cb.get("method", "").lower())(url=callback_url, data=sub(cb.get("data"), **data), headers=cb.get("headers", {})) except: raise Exception(f"Can't send callback to \"{callback_url}\"", 500)
def h_xray(bot, id, chan, args, full_msg): if chan.lower() not in games: return game = games[chan.lower()] if chan.lower() != game.names[game.player].lower(): reply(bot, id, chan, 'Error: it is not your turn.'); return args = args.split() if args: value = args[0] if value in '123': value = int(value) else: reply(bot, id, chan, 'Error: "%s" is not a valid 3-sided die value.' % value); return else: player, opponent = game.player, other_colour(game.player) values = [dv for (dc,dv) in game.dice[player] if dc == opponent] if not values: reply(bot, id, chan, 'Error: %s does not possess any %s dice.' % (player, opponent.lower())); return if not all(v == values[0] for v in values[1:]): reply(bot, id, chan, 'Error: %s has %s dice with different values; you must specify' ' the value to sacrifice.' % (player, opponent.lower())); return value = values[0] try: game.xray(value) except IllegalMove as exc: reply(bot, id, chan, 'Error: %s' % exc) return yield util.sub(end_move(bot, game))
def end_move(bot, game): yield show_board(bot, game, priority=game.winner or game.player) if game.winner: chan1, chan2 = game.names.values() del games[chan1] del games[chan2] yield util.sub(end_session(bot, chan1, chan2))
def h_cancel(bot, id, chan, args, full_msg): # Cancel any existing challenge. if chan.lower() in challenges: opp_chan, colour = challenges.pop(chan.lower()) reply(bot, id, chan, 'Challenge to %s cancelled.' % opp_chan, prefix=False) yield util.sub(end_session(bot, chan)) # Cancel any existing game. if chan.lower() in games: game = games[chan.lower()] [opp_chan] = [c for c in game.names.values() if c.lower()!=chan.lower()] for game_chan in game.names.itervalues(): del games[game_chan.lower()] bot.send_msg(game_chan, 'The game of Upoopia has been cancelled.', no_link=True) yield util.sub(end_session(bot, chan, opp_chan))
def centerAt(self, logicPos): #print 'before centering offset is %s %s'%(self.offset_pos, logicPos) if logicPos == (0,0): print traceback.format_exc() self.offset_pos = util.sub(logicPos, util.div(self.screen_size, 2)) #print 'after centering offset is %s'%(self.offset_pos,) self.update()
def substitute(self, ctx): """Formats request template body with current context""" result = {} for k, v in self.body.items(): if isinstance(v, str): result.update({k: sub(v, **ctx)}) else: result.update({k: v}) return result
def h_resign(bot, id, chan, args, full_msg): if chan.lower() not in games: return game = games[chan.lower()] if chan.lower() != game.names[game.player].lower(): reply(bot, id, chan, 'Error: it is not your turn.'); return try: game.resign() except IllegalMove as exc: reply(bot, id, chan, 'Error: %s' % exc) return yield util.sub(end_move(bot, game))
def look_at(self, eye, center, up): up = normalize(up) f = normalize(sub(center, eye)) s = cross(f, up) u = cross(s, f) matrix = Matrix([ s[0], s[1], s[2], 0, u[0], u[1], u[2], 0, -f[0], -f[1], -f[2], 0, eye[0], eye[1], eye[2], 1, ]).inverse() return matrix * self
def adam(gradfun, allparams, num_iters, step_size, b1=0.9, b2=0.999, eps=1e-8): natparams, params = allparams[:1], allparams[1:] m = zeros_like(params) v = zeros_like(params) i = 0 accumulate = lambda rho, a, b: add(scale(1-rho, a), scale(rho, b)) for i in xrange(num_iters): grad = gradfun(allparams, i) natgrad, grad = grad[:1], grad[1:] m = accumulate(b1, grad, m) # first moment estimate v = accumulate(b2, square(grad), v) # second moment estimate mhat = scale(1./(1 - b1**(i+1)), m) # bias correction vhat = scale(1./(1 - b2**(i+1)), v) update = scale(step_size, div(mhat, add_scalar(eps, sqrt(vhat)))) natparams = sub(natparams, scale(step_size, natgrad)) params = sub(params, update) allparams = concat(natparams, params) return allparams
def intersect(self, o, d): r = self.radius - 0.001 to = util.sub(o, self.center) b = util.dot(to, d) c = util.dot(to, to) - r * r d = b * b - c if d > 0: d = d ** 0.5 t1 = -b - d if t1 > 0: return t1 t2 = -b + d if t2 > 0: return t2 return None
def onScroll(self, evt): pos = evt.GetPosition() logicPos = util.div(pos, float(self.cell_size)) diff = 1 if evt.GetWheelRotation()>0 else -1 self.cell_size += diff if self.cell_size < 1: self.cell_size = 1 elif self.cell_size > 40: self.cell_size = 40 self.calcScreenSize() #make sure mouse is pointing on the centre of the scroll area ( just move the pos so that this _is_ the center ) newScreenPos = util.mul(logicPos, self.cell_size) newScreenDiff = util.sub(newScreenPos, pos) newLogicDiff = util.div(newScreenDiff, self.cell_size) self.offset_pos = util.add(self.offset_pos, newLogicDiff) self.update()
def build_response(self): """Renders response template with substitutions""" if not self.req_handled: raise Exception(f"{self.__class__} doesn't handle any request") if isinstance(self.template.response, list): try: status, body = self.template.response except ValueError as e: raise Exception(f"Invalid response template: {e}", 500) if status not in _CODES: raise Exception(f"Invalid status code in template: {status}", 500) else: status, body = 200, self.template.response self._callback(**self.global_ctx, **self.request_context) resp = sub(body, **self.global_ctx, **self.request_context) return Response(resp, mimetype=self.template.content_type), status
def _build_ctx(self): ctx = { **self.template.get_sub_values(self.data), **self.url_template.get_sub_values(self.path), **self.template.variables } cache_data = None if self.template.key: if self.template.create_cache: self.cache.add_new(self.template.key, ctx) else: if self.template.rule: rules = { k: sub(v, **ctx) for k, v in self.template.rule.items() } cache_data = self.cache.find(self.template.key, **rules) if cache_data: ctx.update(cache_data) return ctx
def h_move(bot, id, chan, args, full_msg, **kwds): if chan.lower() not in games: return game = games[chan.lower()] if chan.lower() != game.names[game.player].lower(): reply(bot, id, chan, 'Error: it is not your turn.'); return args = kwds['a'](args).split() if len(args) < 3: reply(bot, id, chan, 'Error: 3 parameters expected. See "help upoopia".'); return colour, direction, value = args[:3] if direction in '123456': value, direction = direction, value if 'blue'.startswith(colour.lower()): colour = BLACK elif 'red'.startswith(colour.lower()): colour = WHITE else: reply(bot, id, chan, 'Error: "%s" is not a valid colour.' % colour); return if value in '123456': value = int(value) else: reply(bot, id, chan, 'Error: "%s" is not a valid distance.' % value); return if 'left'.startswith(direction.lower()): direction = LEFT elif 'right'.startswith(direction.lower()): direction = RIGHT elif 'up'.startswith(direction.lower()): direction = UP elif 'down'.startswith(direction.lower()): direction = DOWN else: reply(bot, id, chan, 'Error: "%s" is not a valid direction.' % direction); return try: game.move(colour, value, direction) except IllegalMove as e: reply(bot, id, chan, 'Error: %s' % e) return yield util.sub(end_move(bot, game))
def h_self_exit(bot, chan, *args): if chan.lower() in challenges: del challenges[chan.lower()] yield util.sub(end_session(bot, chan))
def rectFilter(self, rect): ps = self.screenPosToLogic(rect.GetPosition().Get()) ps = util.sub(ps, (1,1)) sz = util.div(rect.GetSize().Get(), self.cell_size) sz = util.add(sz, (1,1)) return ['x>=%d AND y>=%d AND x<=%d AND y<=%d'%(ps[0], ps[1], ps[0]+sz[0], ps[1]+sz[1])]
def gradfun(y_n, N, L, eta, phi, psi): objective = lambda (phi, psi): mc_vlb(eta, phi, psi, y_n, N, L) vlb, (phi_grad, psi_grad) = vgrad(objective)((phi, psi)) eta_natgrad = sub(add(eta_prior, saved.stats), eta) return vlb, (eta_natgrad, phi_grad, psi_grad)
def test_sub(): assert sub(5, 2) == 3, "test failed"
def h_upoopia(bot, id, chan, args, full_msg): if not chan: return # Parse arguments. args = args.split() if len(args) >= 2: opp_chan, colour = args[:2] if 'blue'.startswith(colour.lower()): colour = BLACK elif 'red'.startswith(colour.lower()): colour = WHITE else: reply(bot, id, chan, 'Error: "%s" is not a valid colour.' % colour) return elif len(args) >= 1: opp_chan, colour = args[0], None elif len(chan_link.links.get(chan.lower(), set())) == 1: # Implicitly select the single channel to which we are linked. [opp_chan], colour = chan_link.links[chan.lower()], None else: if chan.lower() in challenges: opp_chan, colour = challenges[chan.lower()] bot.send_msg(chan, 'A challenge issued to %s is currently pending.' % opp_chan) elif chan.lower() in games: game = games[chan.lower()] [opp] = [chan for chan in game.names.values() if chan.lower() != chan.lower()] bot.send_msg(chan, 'A game of Upoopia against %s is currently in session.' % opp) else: bot.send_msg(chan, 'No game of Upoopia is active.' ' See \2!help upoopia\2 for starting a game.') return if not opp_chan.startswith('#'): reply(bot, id, chan, 'Error: "%s" is not a valid channel name.' % opp_chan) return elif opp_chan.lower() == chan.lower(): reply(bot, id, chan, 'Error: your opponent must be in a different channel!') return # If not already linked, require operator status. if not chan_link.is_linked(chan, opp_chan): pre_ms, pre_cs = bot.isupport['PREFIX'] umodes = channel.umode_channels[chan.lower()] umodes = umodes.get(id.nick.lower(), '') if not any(m in umodes for m in pre_ms[:pre_ms.find('o')+1]): reply(bot, id, chan, 'Error: only channel operators may initiate a channel link.') return # Acquire the 'upoopia' mode in this channel. if modal.get_mode(chan) == 'upoopia' and chan.lower() in challenges: # If another challenge exists, cancel it. old_opp_chan, colour = challenges.pop(chan.lower()) bot.send_msg(chan, 'Challenge to %s cancelled.' % old_opp_chan) elif modal.get_mode(chan): yield sign('CONTEND_MODE', bot, id, chan) return else: modal.set_mode(chan, 'upoopia') if opp_chan.lower() in challenges: # If a reciprocating challenge exists, immediately start the game. opp_opp_chan, opp_colour = challenges[opp_chan.lower()] if opp_opp_chan.lower() == chan.lower(): del challenges[opp_chan.lower()] yield util.sub(start_game(bot, chan, opp_chan, colour, opp_colour)) return elif chan_link.is_linked(chan, opp_chan) \ and modal.get_mode(opp_chan) in (None, 'upoopia'): # Otherwise, if the opponent channel is still linked and does not # have any pending challenges, also immediately start the game. modal.set_mode(opp_chan, 'upoopia') yield util.sub(start_game(bot, chan, opp_chan, colour, None)) return # Otherwise, just record the challenge. challenges[chan.lower()] = (opp_chan, colour) bot.send_msg(chan, 'Challenge issued: waiting for %s to reciprocate.' % opp_chan)
def visible(self, eye, point): v = util.sub(eye, point) o = point d = util.normalize(v) t = self.intersect(o, d, 0, util.length(v)) return t is None