def install():
    def wrapNextTurn(self):
        if self not in games:
            games.append(self)
        if self.turn == self.players[0]:
            self.player1Time += self.timeInc
        elif self.turn == self.players[1]:
            self.player0Time += self.timeInc
        retval = yield aspects.proceed

    aspects.with_wrap(wrapNextTurn, Match.nextTurn)

    def tick():
        import main
        for i in games:
            if i.turn == i.players[0]:
                i.player0Time -= 1
                if i.player0Time < 0:
                    i.declareWinner(i.players[1], 'Laaaaaag')
            elif i.turn == i.players[1]:
                i.player1Time -= 1
                if i.player1Time < 0:
                    i.declareWinner(i.players[0], 'Laaaaaag')
            else:
                games.remove(i)

        reactor.callLater(1, tick)

    reactor.callWhenRunning(reactor.callLater, 1, tick)
def install():
  def wrapNextTurn(self):
    if self not in games:
      games.append(self)
    if self.turn == self.players[0]:
      self.player1Time += self.timeInc
    elif self.turn == self.players[1]:
      self.player0Time += self.timeInc
    retval = yield aspects.proceed

  aspects.with_wrap(wrapNextTurn, Match.nextTurn)

  def tick():
    import main
    for i in games:
      if i.turn == i.players[0]:
        i.player0Time -= 1
        if i.player0Time < 0:
          i.declareWinner(i.players[1], 'Laaaaaag')
      elif i.turn == i.players[1]:
        i.player1Time -= 1
        if i.player1Time < 0:
          i.declareWinner(i.players[0], 'Laaaaaag')
      else:
        games.remove(i)

    reactor.callLater(.01, tick)

  reactor.callWhenRunning(reactor.callLater, .01, tick)
Example #3
0
def install():
  def wrapNextTurn(self):
    if self not in games:
      games.append(self)
    if self.turn == self.players[0]:
      p = [i for i in self.objects.players]
      p[1].time += self.timeInc
    elif self.turn == self.players[1]:
      p = [i for i in self.objects.players]
      p[0].time += self.timeInc
    retval = yield aspects.proceed

  aspects.with_wrap(wrapNextTurn, Match.nextTurn)

  def tick():
    import main
    for i in games:
      p = [j for j in i.objects.values() if isinstance(j,Player)]
      if i.turn == i.players[0]:
        p[0].time -= 1
        if p[0].time < 0:
          print "2 Wins!"
          i.declareWinner(i.players[1], 'Player 1 Lagged Out, Player 2 Wins')
      elif i.turn == i.players[1]:
        p[1].time -= 1
        if p[1].time < 0:
          print "1 Wins!"
          i.declareWinner(i.players[0], 'Player 2 Lagged Out, Player 1 Wins')
      else:
        games.remove(i)

    reactor.callLater(1, tick)

  reactor.callWhenRunning(reactor.callLater, 1, tick)
Example #4
0
def plot_function(minimum, maximum, dif):
    def fitness_two(xs,ys):
	[maxi,maxj] = xs.shape
	result = zeros(xs.shape,dtype=float)
	for i in range(maxi):
	    for j in range(maxj):
		x = xs[i,j]
		y = ys[i,j]
		sol = np.array([x,y])
		fit=function_fitness(sol)
		result[i,j] = fit

	return result
    dx = dy = dif
    x = np.arange(minimum, maximum, dx)
    y = np.arange(minimum, maximum, dy)
    X,Y = meshgrid(x, y)
    Z = fitness_two(X, Y)
    global fig
    fig = plt.figure()
    ax = subplot(111)
    x, y = (np.random.rand(2, 50))*100
    ea.initPopulation(50)
    global eval
    eval=0
    population = ea.population()
    x = scale_var(population[:,0])
    y = scale_var(population[:,1])
#    print x
#    print y
#    print "\n"
    global line
    line, = ax.plot(x, y, 'wo')
    im = imshow(Z, cmap=cm.jet)
    im.set_interpolation('bilinear')
    save()
    global numberOfTimeSteps,stepframe
    aspects.with_wrap(measureFitness, SSGA.updateWorst)
    ea.run(numberOfTimeSteps*stepframe)
    aspects.without_wrap(measureFitness, SSGA.updateWorst)
    # Clear the figure to make way for the next image.
    plt.clf()
Example #5
0
def study_population(self, individual):

    if individual == "best":
        world.get_fitness = np.min
    elif individual == "worst":
        world.get_fitness = np.max
    elif individual == "mean":
        world.get_fitness = np.mean
    else:
        assert False, "Error, individual '%s' is not known" % individual

    world.wrap_id = aspects.with_wrap(measureFitness, SSGA.updateWorst)
def install():
  def wrapMatch(*args, **kwargs):
    yield aspects.proceed
    f = open('created', 'w')
    f.write('Game created')
    f.close()
    
    
  def wrapStart(*args, **kwargs):
    yield aspects.proceed
    f = open('started', 'w')
    f.write('Game started')
    f.close()

  def wrapDeclareWinner(self, winner, reason):
    f = open('winner', 'w')
    if winner is self.players[0]:
      f.write("Player 0 wins")
    else:
      f.write("Player 1 wins")
    f.close()
    yield aspects.proceed
    reactor.stop()

  aspects.with_wrap(wrapMatch, Match.__init__)
  aspects.with_wrap(wrapStart, Match.start)
  aspects.with_wrap(wrapDeclareWinner, Match.declareWinner)
Example #7
0
def install():
    def wrapMatch(*args, **kwargs):
        yield aspects.proceed
        f = open('created', 'w')
        f.write('Game created')
        f.close()

    def wrapStart(*args, **kwargs):
        yield aspects.proceed
        f = open('started', 'w')
        f.write('Game started')
        f.close()

    def wrapDeclareWinner(self, winner, reason):
        f = open('winner', 'w')
        if winner is self.players[0]:
            f.write("Player 0 wins")
        else:
            f.write("Player 1 wins")
        f.close()
        yield aspects.proceed
        reactor.stop()

    aspects.with_wrap(wrapMatch, Match.__init__)
    aspects.with_wrap(wrapStart, Match.start)
    aspects.with_wrap(wrapDeclareWinner, Match.declareWinner)
Example #8
0
def start(settings):
    """
    Since there's no easy way to detect if autoreloading will be used when the server
    starts, we wrap ``django.core.management.commands.runserver.Command`` to check
    the options directly.

    Note: if ``manage.py runserver`` is not used to start the server, this approach
          may not work.

    ``settings``
      a module that defines:
        ``DASH_TOKEN``
          Required; application token for this application
        ``DASH_RECIPES``
          Optional; a list/tuple of additional recipes to add to the configuration
        ``DASH_LOGGER_LEVEL``
          Optional; shorthand for ``logging.getLogger('fiveruns_dash').setLevel()``
          By default, this is ``logging.WARN``
        ``DASH_CONFIGURE_WITH``
          Optional; function to pass configuration object for manual modification

    """
    global configuration
    if not hasattr(settings, 'DASH_TOKEN'):
        raise ImproperlyConfigured, 'Error configuring fiveruns_dash.django. Is DASH_TOKEN defined?'
    if hasattr(settings, 'DASH_LOGGER_LEVEL'):
        logging.getLogger('fiveruns_dash').setLevel(settings.DASH_LOGGER_LEVEL)
    configuration = fiveruns.dash.configure(app_token=settings.DASH_TOKEN)
    for recipe in _builtin_recipes():
        configuration.add_recipe(recipe)
    _add_framework_metadata()
    if hasattr(settings, 'DASH_RECIPES'):
        logger.info("Adding additional recipes from settings.py")
        for recipe in settings.DASH_RECIPES:
            configuration.add_recipe(*list(recipe))
    if hasattr(settings, 'DASH_CONFIGURE_WITH'):
        settings.DASH_CONFIGURE_WITH(configure)
    aspects.with_wrap(_start_unless_reloading, Command.handle)
Example #9
0
def install():
    def wrapNextTurn(self):
        if self not in games:
            games.append(self)
        if self.turn == self.players[0]:
            p = [i for i in self.objects.players]
            p[1].time += self.timeInc
        elif self.turn == self.players[1]:
            p = [i for i in self.objects.players]
            p[0].time += self.timeInc
        retval = yield aspects.proceed

    aspects.with_wrap(wrapNextTurn, Match.nextTurn)

    def tick():
        import main
        for i in games:
            p = [j for j in i.objects.values() if isinstance(j, Player)]
            if i.turn == i.players[0]:
                p[0].time -= 1
                if p[0].time < 0:
                    print "2 Wins!"
                    i.declareWinner(i.players[1],
                                    'Player 1 Lagged Out, Player 2 Wins')
            elif i.turn == i.players[1]:
                p[1].time -= 1
                if p[1].time < 0:
                    print "1 Wins!"
                    i.declareWinner(i.players[0],
                                    'Player 2 Lagged Out, Player 1 Wins')
            else:
                games.remove(i)

        reactor.callLater(1, tick)

    reactor.callWhenRunning(reactor.callLater, 1, tick)
PASS,FAIL="PASS","FAIL"
import aspects
import os

test,verdict = "wrap a module function inside very simple g_adv",FAIL
try:
    g_adv_executed=0
    def _test_mod_function(x):
        return x+42
    def g_adv(x):
        global g_adv_executed
        g_adv_executed=1
        yield aspects.proceed
    rv=aspects.with_wrap(g_adv,_test_mod_function)
    r=_test_mod_function(42)
    if rv==0 and r==84 and g_adv_executed: verdict=PASS
finally: print verdict,test

test,verdict = "change the arguments",FAIL
try:
    def __test_mod_function(x):
        return x+42
    def g_adv(x):
        yield aspects.proceed(x+1)
    aspects.with_wrap(g_adv,__test_mod_function)
    if __test_mod_function(0)==43: verdict=PASS
finally: print verdict,test

test,verdict = "change the return value",FAIL
try:
    def __test_mod_function(x):
def getsecondmin(albedo):
	min1_albedo = np.ma.masked_array(albedo, albedo == np.amin(albedo, axis=0))
	return np.amin(albedo, axis=0)

def getcloudindex(apparentalbedo, groundalbedo, cloudalbedo):
	return (apparentalbedo - groundalbedo)/(cloudalbedo - groundalbedo)

def getclearsky(cloudindex):
	clearsky = np.zeros_like(cloudindex)
	cond = cloudindex < -0.2
	clearsky[cond] = 1.2
	cond = ((cloudindex >= -0.2) & (cloudindex < 0.8))
	clearsky[cond] = 1 - cloudindex[cond]
	cond = ((cloudindex >= 0.8) & (cloudindex < 1.1))
	clearsky[cond] = (31 - 55 * cloudindex[cond] + 25 * np.power(cloudindex[cond],2)) / 15
	cond = (cloudindex >= 1.1)
	clearsky[cond] = 0.05
	return clearsky

def gettstdatetime(timestamp, tst_hour):
	return np.trunc(timestamp) + tst_hour / 24.

if not cuda_can_help:
	import aspects
	import re
	excluded_functions = ['getsecondmin']
	current_module = sys.modules[__name__]
	methods = current_module.__dict__
	fxs = [ func for name,func in methods.items() if not name in excluded_functions and re.match( r'^get.*',name) ]
	aspects.with_wrap(iterative_broadcast, *fxs)
Example #12
0
	process_radiation(lat, lon, data, root)

	#s = process_validate(year, month, root)
	#draw.getpng(draw.matrixtogrey(data[15]),'prueba.png')
	nc.close(root)
	show("Process finished.\n")

def show_times(*args):
	begin = datetime.now()
	result = yield aspects.proceed(*args)
	end = datetime.now()
	say("\t[time consumed: %.2f seconds]\n" % (end - begin).total_seconds())
	yield aspects.return_stop(result)

import aspects
import re
current_module = sys.modules[__name__]
methods = current_module.__dict__
fxs = [ func for name,func in methods.items() if re.match( r'^process.*',name) or re.match( r'workwith',name) ]
aspects.with_wrap(show_times, *fxs)


#import cProfile, pstats, io
#pr = cProfile.Profile()
#pr.enable()
workwith(sys.argv[1], sys.argv[2], sys.argv[3])
#pr.disable()
#s = io.StringIO()
#ps = pstats.Stats(pr, stream=s)
#ps.dump_stats('profile_results')
import aspects
import os

test, verdict = "wrap a module function inside very simple g_adv", FAIL
try:
    g_adv_executed = 0

    def _test_mod_function(x):
        return x + 42

    def g_adv(x):
        global g_adv_executed
        g_adv_executed = 1
        yield aspects.proceed

    rv = aspects.with_wrap(g_adv, _test_mod_function)
    r = _test_mod_function(42)
    if rv == 0 and r == 84 and g_adv_executed: verdict = PASS
finally:
    print verdict, test

test, verdict = "change the arguments", FAIL
try:

    def __test_mod_function(x):
        return x + 42

    def g_adv(x):
        yield aspects.proceed(x + 1)

    aspects.with_wrap(g_adv, __test_mod_function)
Example #14
0
def getclearsky(cloudindex):
    clearsky = np.zeros_like(cloudindex)
    cond = cloudindex < -0.2
    clearsky[cond] = 1.2
    cond = ((cloudindex >= -0.2) & (cloudindex < 0.8))
    clearsky[cond] = 1 - cloudindex[cond]
    cond = ((cloudindex >= 0.8) & (cloudindex < 1.1))
    clearsky[cond] = (31 - 55 * cloudindex[cond] +
                      25 * np.power(cloudindex[cond], 2)) / 15
    cond = (cloudindex >= 1.1)
    clearsky[cond] = 0.05
    return clearsky


def gettstdatetime(timestamp, tst_hour):
    return np.trunc(timestamp) + tst_hour / 24.


if not cuda_can_help:
    import aspects
    import re
    excluded_functions = ['getsecondmin']
    current_module = sys.modules[__name__]
    methods = current_module.__dict__
    fxs = [
        func for name, func in methods.items()
        if not name in excluded_functions and re.match(r'^get.*', name)
    ]
    aspects.with_wrap(iterative_broadcast, *fxs)