<commit_before>#!/usr/bin/python

import os
import sys
import argparse
import traceback
from decimal import Decimal,InvalidOperation
from group import Group,UnsortedInputGrouper

class ResampleGroup(Group):
    def __init__(self, tup):
        super(ResampleGroup, self).__init__(tup)
        self.point = None
        self.jdelim = args.delimiter if args.delimiter != None else ' '

    def add(self, chunks):
        npoint = (Decimal(chunks[args.xdata]), Decimal(chunks[args.ydata]))

        if args.begin:
            self.x = args.begin
            while self.x < npoint[0]:
                if len(self.tup) > 0:
                    args.outfile.write(self.jdelim.join(self.tup) + self.jdelim)
                args.outfile.write(str(self.x) + self.jdelim + str(npoint[1]) + '\n')
                self.x += args.frequency

        elif args.sync or (npoint[0] % args.frequency) == 0:
            self.x = npoint[0]
        else:
            self.x = npoint[0] - (npoint[0] % args.frequency) + args.frequency
        self.point = npoint
        if args.expand:
            self.add = self.addAfterExpand
        else:
            self.add = self.addAfter

    def addAfter(self, chunks):
        if args.terminate and self.x > args.terminate:
            self.add = addNothing
            return

        npoint = (Decimal(chunks[args.xdata]), Decimal(chunks[args.ydata]))
        if npoint[0] >= self.x:
            y = args.interpolatef(self.point, npoint, self.x)

            if len(self.tup) > 0:
                args.outfile.write(self.jdelim.join(self.tup) + self.jdelim)
            args.outfile.write(str(self.x) + self.jdelim + str(y) + '\n')

            if self.x != npoint[0] and (npoint[0] % args.frequency) == 0:
                self.x = npoint[0]
            else:
                self.x = npoint[0] - (npoint[0] % args.frequency) + args.frequency
        self.point = npoint

    def addAfterExpand(self, chunks):
        if args.terminate and self.x > args.terminate:
            self.add = addNothing
            return

        npoint = (Decimal(chunks[args.xdata]), Decimal(chunks[args.ydata]))
        if npoint[0] >= self.x:
            # Unwind to compute first two points, so future points can be computed via deltas
            y = args.interpolatef(self.point, npoint, self.x)
            yd = args.interpolatef(self.point, npoint, self.x + args.frequency) - y
            while npoint[0] >= self.x:
                if len(self.tup) > 0:
                    args.outfile.write(self.jdelim.join(self.tup) + self.jdelim)
                args.outfile.write(str(self.x) + self.jdelim + str(y) + '\n')
                self.x += args.frequency
                y += yd
        self.point = npoint

    def addNothing(self, chunks):
        pass

    def done(self):
        while args.terminate and self.x <= args.terminate:
            if len(self.tup) > 0:
                args.outfile.write(self.jdelim.join(self.tup) + self.jdelim)
            args.outfile.write(str(self.x) + self.jdelim + str(self.point[1]) + '\n')
            self.x += args.frequency

def interp_linear(p1, p2, x):
    try:
        return p1[1] + (p2[1] - p1[1]) * (x - p1[0]) / (p2[0] - p1[0])
    except InvalidOperation:
        return p1[1]   # p2[0] == p1[0]

def interp_none(p1, p2, x):
    return p1[1]

if __name__ == "__main__":
    # set up command line args
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\
                                     description='Resample the data points with a different frequency')
    parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
    parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
    parser.add_argument('-f', '--frequency', type=Decimal, default=Decimal('1'))
    parser.add_argument('-i', '--interpolate', choices=['linear', 'none'], default='linear')
    parser.add_argument('-s', '--sync', action='store_true', default=False)
    parser.add_argument('-b', '--begin', type=Decimal, default=None, help='value to begin resampling at')
    parser.add_argument('-t', '--terminate', type=Decimal, default=None, help='value to terminate resampling at')
    parser.add_argument('-e', '--expand', action='store_true', default=False)
    parser.add_argument('-x', '--xdata', type=int, default=0)
    parser.add_argument('-y', '--ydata', type=int, default=1)
    parser.add_argument('-g', '--group', nargs='+', type=int, default=[])
    parser.add_argument('-d', '--delimiter', default=None)
    args = parser.parse_args()
    if args.begin and args.sync:
        raise Exception('Cannot specify both sync and begin parameters')
    args.interpolatef = getattr(sys.modules[__name__], 'interp_'+args.interpolate)

    grouper = UnsortedInputGrouper(args.infile, ResampleGroup, args.group, args.delimiter)
    grouper.group()
<commit_msg>fixed bug<commit_after>#!/usr/bin/python

import os
import sys
import argparse
import traceback
from decimal import Decimal,InvalidOperation
from group import Group,UnsortedInputGrouper

class ResampleGroup(Group):
    def __init__(self, tup):
        super(ResampleGroup, self).__init__(tup)
        self.point = None
        self.jdelim = args.delimiter if args.delimiter != None else ' '

    def add(self, chunks):
        npoint = (Decimal(chunks[args.xdata]), Decimal(chunks[args.ydata]))

        if args.begin:
            self.x = args.begin
            while self.x < npoint[0]:
                if len(self.tup) > 0:
                    args.outfile.write(self.jdelim.join(self.tup) + self.jdelim)
                args.outfile.write(str(self.x) + self.jdelim + str(npoint[1]) + '\n')
                self.x += args.frequency

        elif args.sync or (npoint[0] % args.frequency) == 0:
            self.x = npoint[0]
        else:
            self.x = npoint[0] - (npoint[0] % args.frequency) + args.frequency
        self.point = npoint
        if args.expand:
            self.add = self.addAfterExpand
        else:
            self.add = self.addAfter

    def addAfter(self, chunks):
        if args.terminate and self.x > args.terminate:
            self.add = self.addNothing
            return

        npoint = (Decimal(chunks[args.xdata]), Decimal(chunks[args.ydata]))
        if npoint[0] >= self.x:
            y = args.interpolatef(self.point, npoint, self.x)

            if len(self.tup) > 0:
                args.outfile.write(self.jdelim.join(self.tup) + self.jdelim)
            args.outfile.write(str(self.x) + self.jdelim + str(y) + '\n')

            if self.x != npoint[0] and (npoint[0] % args.frequency) == 0:
                self.x = npoint[0]
            else:
                self.x = npoint[0] - (npoint[0] % args.frequency) + args.frequency
        self.point = npoint

    def addAfterExpand(self, chunks):
        if args.terminate and self.x > args.terminate:
            self.add = self.addNothing
            return

        npoint = (Decimal(chunks[args.xdata]), Decimal(chunks[args.ydata]))
        if npoint[0] >= self.x:
            # Unwind to compute first two points, so future points can be computed via deltas
            y = args.interpolatef(self.point, npoint, self.x)
            yd = args.interpolatef(self.point, npoint, self.x + args.frequency) - y
            while npoint[0] >= self.x:
                if len(self.tup) > 0:
                    args.outfile.write(self.jdelim.join(self.tup) + self.jdelim)
                args.outfile.write(str(self.x) + self.jdelim + str(y) + '\n')
                self.x += args.frequency
                y += yd
        self.point = npoint

    def addNothing(self, chunks):
        pass

    def done(self):
        while args.terminate and self.x <= args.terminate:
            if len(self.tup) > 0:
                args.outfile.write(self.jdelim.join(self.tup) + self.jdelim)
            args.outfile.write(str(self.x) + self.jdelim + str(self.point[1]) + '\n')
            self.x += args.frequency

def interp_linear(p1, p2, x):
    try:
        return p1[1] + (p2[1] - p1[1]) * (x - p1[0]) / (p2[0] - p1[0])
    except InvalidOperation:
        return p1[1]   # p2[0] == p1[0]

def interp_none(p1, p2, x):
    return p1[1]

if __name__ == "__main__":
    # set up command line args
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\
                                     description='Resample the data points with a different frequency')
    parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
    parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
    parser.add_argument('-f', '--frequency', type=Decimal, default=Decimal('1'))
    parser.add_argument('-i', '--interpolate', choices=['linear', 'none'], default='linear')
    parser.add_argument('-s', '--sync', action='store_true', default=False)
    parser.add_argument('-b', '--begin', type=Decimal, default=None, help='value to begin resampling at')
    parser.add_argument('-t', '--terminate', type=Decimal, default=None, help='value to terminate resampling at')
    parser.add_argument('-e', '--expand', action='store_true', default=False)
    parser.add_argument('-x', '--xdata', type=int, default=0)
    parser.add_argument('-y', '--ydata', type=int, default=1)
    parser.add_argument('-g', '--group', nargs='+', type=int, default=[])
    parser.add_argument('-d', '--delimiter', default=None)
    args = parser.parse_args()
    if args.begin and args.sync:
        raise Exception('Cannot specify both sync and begin parameters')
    args.interpolatef = getattr(sys.modules[__name__], 'interp_'+args.interpolate)

    grouper = UnsortedInputGrouper(args.infile, ResampleGroup, args.group, args.delimiter)
    grouper.group()
<|endoftext|>


<commit_before>from collections import deque
import copy
import heapq

from edge import DummyEdgeEnd

class AbstractSimulationEvent(object):
    def process_start(self):
        return frozenset()
    def process_end(self, world, stats):
        return frozenset()

class PheromoneVaporization(AbstractSimulationEvent):
    MULTIPLIER = 0.8
    PERIOD = 100
    TRIGGER_LEVEL = 100
    def __init__(self, end_time, ant_count):
        self.end_time = end_time
        self.ant_count = ant_count
    def process_end(self, world, stats):
        changed = []
        max_pheromone = world.get_max_pheromone_level()
        if max_pheromone >= self.TRIGGER_LEVEL:
            for edge in world.edges:
                for edge_end in (edge.a_end, edge.b_end):
                    new = max(0.0, edge_end.pheromone_level*self.MULTIPLIER)
                    if edge_end.pheromone_level!=new:
                        changed.append(edge_end.edge)
                        edge_end.pheromone_level = new
        return PheromoneVaporization(self.end_time+self.PERIOD, self.ant_count), frozenset(changed)

class AbstractAntMove(AbstractSimulationEvent):
    def __init__(self, ant, origin, destination, end_time, pheromone_to_drop, trip_stats):
        self.ant = ant
        self.origin = origin
        self.destination = destination
        if self.origin is not None and self.destination is not None:
            if self.origin.edge is not None and self.destination.edge is not None:
                #print 'origin', self.origin
                #print 'destination', self.destination
                assert self.origin.edge == self.destination.edge
        self.end_time = end_time
        self.pheromone_to_drop = pheromone_to_drop
        self.trip_stats = trip_stats
    def process_start(self):
        self.origin.drop_pheromone(self.pheromone_to_drop)
        #print "1 dropping %s pheromone on %s" % (self.pheromone_to_drop, self.origin)
        return frozenset((self.origin.edge, self.origin.point))
    def process_end(self, world, stats):
        changed = [self.destination.edge]
        self.trip_stats.edge_visited(self.destination.edge)
        self.destination.drop_pheromone(self.pheromone_to_drop)
        #print "2 dropping %s pheromone on %s" % (self.pheromone_to_drop, self.destination)
        if not self.destination.point.is_anthill() and self.destination.point.food > 0 and not self.ant.food:
            changed.append(self.destination.point)
            self.trip_stats.food_found()
            self.destination.point.food -= 1
            self.ant.food += 1
            stats.food_found(self.trip_stats)
            stats.present()
        elif self.destination.point.is_anthill():
            if self.ant.food:
                changed.append(self.destination.point)
                self.destination.point.food += self.ant.food
                self.trip_stats.back_home()
                new_ant = self.ant.__class__(self.ant.world_parameters)
                return AntRestartMove(new_ant, anthill=DummyEdgeEnd(self.destination.point), end_time=world.elapsed_time), frozenset(changed)
            else:
                self.trip_stats.reset_route()
        new_destination_edge, pheromone_to_drop = self.ant.tick(self.destination.point)
        assert new_destination_edge in (end.edge for end in self.destination.point.edge_ends), 'Illegal ant move'
        self.trip_stats.normal_move(new_destination_edge.cost)
        new_destination = new_destination_edge.get_other_end_by_point(self.destination.point)
        origin = new_destination_edge.get_other_end(new_destination)
        end_time = world.elapsed_time + new_destination_edge.cost
        return AntMove(
            ant=self.ant,
            origin=origin,
            destination=new_destination,
            end_time=end_time,
            pheromone_to_drop=pheromone_to_drop,
            trip_stats=self.trip_stats,
        ), frozenset(changed)
    def __cmp__(self, other):
        return self.end_time - other.end_time
    def __repr__(self):
        return '%s@%s' % (self.__class__.__name__, self.end_time,)

class AntRestartMove(AbstractAntMove):
    def __init__(self, ant, anthill, end_time):
        super(AntRestartMove, self).__init__(ant, None, anthill, end_time=end_time, pheromone_to_drop=0, trip_stats=TripStats())
    def process_start(self):
        return frozenset()

class AntStartMove(AntRestartMove):
    def __init__(self, ant, anthill):
        super(AntStartMove, self).__init__(ant, anthill, end_time=0)

class AntMove(AbstractAntMove):
    pass

class TripStats(object):
    def __init__(self):
        self.food_found_after = 0, 0
        self.total_cost = 0
        self.total_moves = 0
        self.visited = deque()
    def reset_route(self):
        self.visited = deque()
    def food_found(self):
        self.food_found_after = self.total_moves, self.total_cost
    def normal_move(self, cost):
        self.total_moves += 1
        self.total_cost += cost
    def edge_visited(self, edge):
        self.visited.append(edge)
    def back_home(self):
        #print 'moves: %s, cost: %s, to find: %s' % (self.total_moves, self.total_cost, self.food_found_after)
        pass

class QueenStats(object):
    def __init__(self, reality, number_of_ants):
        self.reality = reality
        self.food_discovered = 0
        self.moves_leading_to_food_being_found = 0
        self.number_of_ants = number_of_ants
        self.best_finding_cost = 999999999
        self.last_cost = 0
        self.last_route = []
    def food_found(self, trip_stats):
        self.food_discovered += 1
        self.last_cost = trip_stats.food_found_after[1]
        self.moves_leading_to_food_being_found += trip_stats.food_found_after[0]
        self.best_finding_cost = min(self.best_finding_cost, trip_stats.food_found_after[1])
        self.last_route = copy.copy(trip_stats.visited)
    def present(self):
        avg_cost = (self.reality.world.elapsed_time*self.number_of_ants)/self.food_discovered
        avg_moves = self.moves_leading_to_food_being_found/self.food_discovered
        avg_pheromone = self.reality.world.get_average_pheromone_level()
        print 'food found: %d, best: %.3f, avg. pheromone: %.3f, avg. moves to find: %d, avg. cost to find: %.3f, time: %d, last_cost: %s' % (self.food_discovered, self.best_finding_cost, avg_pheromone, avg_moves, avg_cost, self.reality.world.elapsed_time, self.last_cost)

class AbstractSimulation(object):
    def __init__(self, reality, antmoves, stats):
        self.reality = reality
        self.antmoves = antmoves
        heapq.heapify(antmoves)
        self.stats = stats
        self.ticks = 0
    def tick(self):
        ant_move = heapq.heappop(self.antmoves)
        self.reality.world.elapsed_time = ant_move.end_time # simulation is now at the point of ant_move.ant arriving at ant_move.destination
        #print 'processing ant_move', ant_move.end_time
        #print '[%f] %s is moving to %s, %s' % (self.reality.world.elapsed_time, ant_move.ant, ant_move.destination.point, ant_move.ant.food)
        #print sum([food_point.food for food_point in self.reality.world.get_food_points()])
        new_antmove, changed_items_end = ant_move.process_end(self.reality.world, self.stats)
        assert not self.reality.world.elapsed_time > ant_move.end_time
        changed_items_start = new_antmove.process_start()
        assert changed_items_start is not None, new_antmove
        heapq.heappush(self.antmoves, new_antmove)
        self.ticks += 1
        return changed_items_start & changed_items_end, self.stats

class TickStepSimulation(AbstractSimulation):
    def advance(self):
        print 'ticks', self.ticks
        if self.reality.is_resolved():
            return [], True, None
        tick_changed_items, stats = self.tick()
        return tick_changed_items, False, stats.last_route

class MultiSpawnStepSimulation(AbstractSimulation):
    def __init__(self, reality, *args, **kwargs):
        super(MultiSpawnStepSimulation, self).__init__(reality, *args, **kwargs)
        self.spawn_amount = 100
        self.anthills = reality.world.get_anthills()
    def advance(self):
        if self.reality.is_resolved():
            return [], True, None
        anthill_food_pre_tick = sum([anthill.food for anthill in self.anthills])
        changed_items = set()
        amount = 0
        while amount <= self.spawn_amount:
            tick_changed_items, stats = self.tick()
            changed_items.update(tick_changed_items)
            anthill_food_post_tick = sum([anthill.food for anthill in self.anthills])
            if anthill_food_post_tick != anthill_food_pre_tick+amount:
                if self.reality.is_resolved():
                    break
                amount += 1
        return changed_items, False, stats.last_route

class SpawnStepSimulation(MultiSpawnStepSimulation):
    def __init__(self, reality, *args, **kwargs):
        super(SpawnStepSimulation, self).__init__(reality, *args, **kwargs)
        self.spawn_amount = 1

class Simulator(object):
    def __init__(self, reality, simulation_class):
        self.reality = reality
        self.simulation_class = simulation_class
    def simulate(self, queen, amount_of_ants):
        ant_classes = queen.spawn_ants(amount_of_ants)
        ants = [ant_class(self.reality.environment_parameters) for ant_class in ant_classes]
        anthills = self.reality.world.get_anthills()
        antmoves = list(self.get_start_antmoves(ants, anthills))
        antmoves.append(PheromoneVaporization(PheromoneVaporization.PERIOD, len(ants)))
        stats = QueenStats(self.reality, len(ants))
        return self.simulation_class(self.reality, antmoves, stats)
    def get_results(self, simulation):
        ticks = simulation.ticks
        elapsed_time = self.reality.world.elapsed_time
        self.reality.world.reset()
        return elapsed_time, ticks
    def get_start_antmoves(self, ants, anthills):
        """ iterator """
        counter = 0
        number_of_anthills = len(anthills)
        anthills = list(anthills)
        for ant in ants:
            anthill = anthills[counter % number_of_anthills]
            yield AntStartMove(ant, DummyEdgeEnd(anthill))
            counter += 1

<commit_msg>Increase frame rendering frequency in MultiSpawn mode<commit_after>from collections import deque
import copy
import heapq

from edge import DummyEdgeEnd

class AbstractSimulationEvent(object):
    def process_start(self):
        return frozenset()
    def process_end(self, world, stats):
        return frozenset()

class PheromoneVaporization(AbstractSimulationEvent):
    MULTIPLIER = 0.8
    PERIOD = 100
    TRIGGER_LEVEL = 100
    def __init__(self, end_time, ant_count):
        self.end_time = end_time
        self.ant_count = ant_count
    def process_end(self, world, stats):
        changed = []
        max_pheromone = world.get_max_pheromone_level()
        if max_pheromone >= self.TRIGGER_LEVEL:
            for edge in world.edges:
                for edge_end in (edge.a_end, edge.b_end):
                    new = max(0.0, edge_end.pheromone_level*self.MULTIPLIER)
                    if edge_end.pheromone_level!=new:
                        changed.append(edge_end.edge)
                        edge_end.pheromone_level = new
        return PheromoneVaporization(self.end_time+self.PERIOD, self.ant_count), frozenset(changed)

class AbstractAntMove(AbstractSimulationEvent):
    def __init__(self, ant, origin, destination, end_time, pheromone_to_drop, trip_stats):
        self.ant = ant
        self.origin = origin
        self.destination = destination
        if self.origin is not None and self.destination is not None:
            if self.origin.edge is not None and self.destination.edge is not None:
                #print 'origin', self.origin
                #print 'destination', self.destination
                assert self.origin.edge == self.destination.edge
        self.end_time = end_time
        self.pheromone_to_drop = pheromone_to_drop
        self.trip_stats = trip_stats
    def process_start(self):
        self.origin.drop_pheromone(self.pheromone_to_drop)
        #print "1 dropping %s pheromone on %s" % (self.pheromone_to_drop, self.origin)
        return frozenset((self.origin.edge, self.origin.point))
    def process_end(self, world, stats):
        changed = [self.destination.edge]
        self.trip_stats.edge_visited(self.destination.edge)
        self.destination.drop_pheromone(self.pheromone_to_drop)
        #print "2 dropping %s pheromone on %s" % (self.pheromone_to_drop, self.destination)
        if not self.destination.point.is_anthill() and self.destination.point.food > 0 and not self.ant.food:
            changed.append(self.destination.point)
            self.trip_stats.food_found()
            self.destination.point.food -= 1
            self.ant.food += 1
            stats.food_found(self.trip_stats)
            stats.present()
        elif self.destination.point.is_anthill():
            if self.ant.food:
                changed.append(self.destination.point)
                self.destination.point.food += self.ant.food
                self.trip_stats.back_home()
                new_ant = self.ant.__class__(self.ant.world_parameters)
                return AntRestartMove(new_ant, anthill=DummyEdgeEnd(self.destination.point), end_time=world.elapsed_time), frozenset(changed)
            else:
                self.trip_stats.reset_route()
        new_destination_edge, pheromone_to_drop = self.ant.tick(self.destination.point)
        assert new_destination_edge in (end.edge for end in self.destination.point.edge_ends), 'Illegal ant move'
        self.trip_stats.normal_move(new_destination_edge.cost)
        new_destination = new_destination_edge.get_other_end_by_point(self.destination.point)
        origin = new_destination_edge.get_other_end(new_destination)
        end_time = world.elapsed_time + new_destination_edge.cost
        return AntMove(
            ant=self.ant,
            origin=origin,
            destination=new_destination,
            end_time=end_time,
            pheromone_to_drop=pheromone_to_drop,
            trip_stats=self.trip_stats,
        ), frozenset(changed)
    def __cmp__(self, other):
        return self.end_time - other.end_time
    def __repr__(self):
        return '%s@%s' % (self.__class__.__name__, self.end_time,)

class AntRestartMove(AbstractAntMove):
    def __init__(self, ant, anthill, end_time):
        super(AntRestartMove, self).__init__(ant, None, anthill, end_time=end_time, pheromone_to_drop=0, trip_stats=TripStats())
    def process_start(self):
        return frozenset()

class AntStartMove(AntRestartMove):
    def __init__(self, ant, anthill):
        super(AntStartMove, self).__init__(ant, anthill, end_time=0)

class AntMove(AbstractAntMove):
    pass

class TripStats(object):
    def __init__(self):
        self.food_found_after = 0, 0
        self.total_cost = 0
        self.total_moves = 0
        self.visited = deque()
    def reset_route(self):
        self.visited = deque()
    def food_found(self):
        self.food_found_after = self.total_moves, self.total_cost
    def normal_move(self, cost):
        self.total_moves += 1
        self.total_cost += cost
    def edge_visited(self, edge):
        self.visited.append(edge)
    def back_home(self):
        #print 'moves: %s, cost: %s, to find: %s' % (self.total_moves, self.total_cost, self.food_found_after)
        pass

class QueenStats(object):
    def __init__(self, reality, number_of_ants):
        self.reality = reality
        self.food_discovered = 0
        self.moves_leading_to_food_being_found = 0
        self.number_of_ants = number_of_ants
        self.best_finding_cost = 999999999
        self.last_cost = 0
        self.last_route = []
    def food_found(self, trip_stats):
        self.food_discovered += 1
        self.last_cost = trip_stats.food_found_after[1]
        self.moves_leading_to_food_being_found += trip_stats.food_found_after[0]
        self.best_finding_cost = min(self.best_finding_cost, trip_stats.food_found_after[1])
        self.last_route = copy.copy(trip_stats.visited)
    def present(self):
        avg_cost = (self.reality.world.elapsed_time*self.number_of_ants)/self.food_discovered
        avg_moves = self.moves_leading_to_food_being_found/self.food_discovered
        avg_pheromone = self.reality.world.get_average_pheromone_level()
        print 'food found: %d, best: %.3f, avg. pheromone: %.3f, avg. moves to find: %d, avg. cost to find: %.3f, time: %d, last_cost: %s' % (self.food_discovered, self.best_finding_cost, avg_pheromone, avg_moves, avg_cost, self.reality.world.elapsed_time, self.last_cost)

class AbstractSimulation(object):
    def __init__(self, reality, antmoves, stats):
        self.reality = reality
        self.antmoves = antmoves
        heapq.heapify(antmoves)
        self.stats = stats
        self.ticks = 0
    def tick(self):
        ant_move = heapq.heappop(self.antmoves)
        self.reality.world.elapsed_time = ant_move.end_time # simulation is now at the point of ant_move.ant arriving at ant_move.destination
        #print 'processing ant_move', ant_move.end_time
        #print '[%f] %s is moving to %s, %s' % (self.reality.world.elapsed_time, ant_move.ant, ant_move.destination.point, ant_move.ant.food)
        #print sum([food_point.food for food_point in self.reality.world.get_food_points()])
        new_antmove, changed_items_end = ant_move.process_end(self.reality.world, self.stats)
        assert not self.reality.world.elapsed_time > ant_move.end_time
        changed_items_start = new_antmove.process_start()
        assert changed_items_start is not None, new_antmove
        heapq.heappush(self.antmoves, new_antmove)
        self.ticks += 1
        return changed_items_start & changed_items_end, self.stats

class TickStepSimulation(AbstractSimulation):
    def advance(self):
        print 'ticks', self.ticks
        if self.reality.is_resolved():
            return [], True, None
        tick_changed_items, stats = self.tick()
        return tick_changed_items, False, stats.last_route

class MultiSpawnStepSimulation(AbstractSimulation):
    def __init__(self, reality, *args, **kwargs):
        super(MultiSpawnStepSimulation, self).__init__(reality, *args, **kwargs)
        self.spawn_amount = 50
        self.anthills = reality.world.get_anthills()
    def advance(self):
        if self.reality.is_resolved():
            return [], True, None
        anthill_food_pre_tick = sum([anthill.food for anthill in self.anthills])
        changed_items = set()
        amount = 0
        while amount <= self.spawn_amount:
            tick_changed_items, stats = self.tick()
            changed_items.update(tick_changed_items)
            anthill_food_post_tick = sum([anthill.food for anthill in self.anthills])
            if anthill_food_post_tick != anthill_food_pre_tick+amount:
                if self.reality.is_resolved():
                    break
                amount += 1
        return changed_items, False, stats.last_route

class SpawnStepSimulation(MultiSpawnStepSimulation):
    def __init__(self, reality, *args, **kwargs):
        super(SpawnStepSimulation, self).__init__(reality, *args, **kwargs)
        self.spawn_amount = 1

class Simulator(object):
    def __init__(self, reality, simulation_class):
        self.reality = reality
        self.simulation_class = simulation_class
    def simulate(self, queen, amount_of_ants):
        ant_classes = queen.spawn_ants(amount_of_ants)
        ants = [ant_class(self.reality.environment_parameters) for ant_class in ant_classes]
        anthills = self.reality.world.get_anthills()
        antmoves = list(self.get_start_antmoves(ants, anthills))
        antmoves.append(PheromoneVaporization(PheromoneVaporization.PERIOD, len(ants)))
        stats = QueenStats(self.reality, len(ants))
        return self.simulation_class(self.reality, antmoves, stats)
    def get_results(self, simulation):
        ticks = simulation.ticks
        elapsed_time = self.reality.world.elapsed_time
        self.reality.world.reset()
        return elapsed_time, ticks
    def get_start_antmoves(self, ants, anthills):
        """ iterator """
        counter = 0
        number_of_anthills = len(anthills)
        anthills = list(anthills)
        for ant in ants:
            anthill = anthills[counter % number_of_anthills]
            yield AntStartMove(ant, DummyEdgeEnd(anthill))
            counter += 1

<|endoftext|>


<commit_before>"""
byceps.blueprints.user_avatar.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from flask import abort, g, request

from ...services.image import service as image_service
from ...services.user_avatar import service as avatar_service
from ...util.framework.blueprint import create_blueprint
from ...util.framework.flash import flash_success
from ...util.image.models import ImageType
from ...util.templating import templated
from ...util.views import redirect_to, respond_no_content

from .forms import UpdateForm
from . import signals

blueprint = create_blueprint('user_avatar', __name__)

ALLOWED_IMAGE_TYPES = frozenset([
    ImageType.jpeg,
    ImageType.png,
])

@blueprint.route('/me/avatar/update')
@templated
def update_form(erroneous_form=None):
    """Show a form to update the current user's avatar image."""
    get_current_user_or_404()

    form = erroneous_form if erroneous_form else UpdateForm()

    image_type_names = image_service.get_image_type_names(ALLOWED_IMAGE_TYPES)

    return {
        'form': form,
        'allowed_types': image_type_names,
        'maximum_dimensions': avatar_service.MAXIMUM_DIMENSIONS,
    }

@blueprint.route('/me/avatar', methods=['POST'])
def update():
    """Update the current user's avatar image."""
    user = get_current_user_or_404()._user

    # Make `InputRequired` work on `FileField`.
    form_fields = request.form.copy()
    if request.files:
        form_fields.update(request.files)

    form = UpdateForm(form_fields)

    if not form.validate():
        return update_form(form)

    image = request.files.get('image')
    if not image or not image.filename:
        abort(400, 'No file to upload has been specified.')

    try:
        avatar_service.update_avatar_image(user, image.stream,
                                           allowed_types=ALLOWED_IMAGE_TYPES)
    except avatar_service.ImageTypeProhibited as e:
        abort(400, str(e))
    except FileExistsError:
        abort(409, 'File already exists, not overwriting.')

    flash_success('Dein Avatarbild wurde aktualisiert.', icon='upload')
    signals.avatar_updated.send(None, user_id=user.id)

    return redirect_to('user.view_current')

@blueprint.route('/me/avatar', methods=['DELETE'])
@respond_no_content
def delete():
    """Remove the current user's avatar image."""
    user = get_current_user_or_404()._user

    avatar_service.remove_avatar_image(user)

    flash_success('Dein Avatarbild wurde entfernt.')

def get_current_user_or_404():
    user = g.current_user

    if not user.is_active:
        abort(404)

    return user
<commit_msg>Extract function<commit_after>"""
byceps.blueprints.user_avatar.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from flask import abort, g, request

from ...services.image import service as image_service
from ...services.user_avatar import service as avatar_service
from ...util.framework.blueprint import create_blueprint
from ...util.framework.flash import flash_success
from ...util.image.models import ImageType
from ...util.templating import templated
from ...util.views import redirect_to, respond_no_content

from .forms import UpdateForm
from . import signals

blueprint = create_blueprint('user_avatar', __name__)

ALLOWED_IMAGE_TYPES = frozenset([
    ImageType.jpeg,
    ImageType.png,
])

@blueprint.route('/me/avatar/update')
@templated
def update_form(erroneous_form=None):
    """Show a form to update the current user's avatar image."""
    get_current_user_or_404()

    form = erroneous_form if erroneous_form else UpdateForm()

    image_type_names = image_service.get_image_type_names(ALLOWED_IMAGE_TYPES)

    return {
        'form': form,
        'allowed_types': image_type_names,
        'maximum_dimensions': avatar_service.MAXIMUM_DIMENSIONS,
    }

@blueprint.route('/me/avatar', methods=['POST'])
def update():
    """Update the current user's avatar image."""
    user = get_current_user_or_404()._user

    # Make `InputRequired` work on `FileField`.
    form_fields = request.form.copy()
    if request.files:
        form_fields.update(request.files)

    form = UpdateForm(form_fields)

    if not form.validate():
        return update_form(form)

    image = request.files.get('image')

    _update(user, image)

    flash_success('Dein Avatarbild wurde aktualisiert.', icon='upload')
    signals.avatar_updated.send(None, user_id=user.id)

    return redirect_to('user.view_current')

def _update(user, image):
    if not image or not image.filename:
        abort(400, 'No file to upload has been specified.')

    try:
        avatar_service.update_avatar_image(user, image.stream,
                                           allowed_types=ALLOWED_IMAGE_TYPES)
    except avatar_service.ImageTypeProhibited as e:
        abort(400, str(e))
    except FileExistsError:
        abort(409, 'File already exists, not overwriting.')

@blueprint.route('/me/avatar', methods=['DELETE'])
@respond_no_content
def delete():
    """Remove the current user's avatar image."""
    user = get_current_user_or_404()._user

    avatar_service.remove_avatar_image(user)

    flash_success('Dein Avatarbild wurde entfernt.')

def get_current_user_or_404():
    user = g.current_user

    if not user.is_active:
        abort(404)

    return user
<|endoftext|>


<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4

#    Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from anvil import log

LOG = log.getLogger(__name__)

def get_shared_params(cfg):
    mp = dict()

    host_ip = cfg.get('host', 'ip')
    mp['service_host'] = host_ip

    # Components of the various endpoints
    swift_host = cfg.getdefaulted('swift', 'swift_host', host_ip)
    swift_port = cfg.getdefaulted('swift', 'swift_port', '8080')
    swift_proto = cfg.getdefaulted('swift', 'swift_protocol', 'http')
    swift_uri = utils.make_url(swift_proto, swift_host, swift_port)
    mp['endpoints'] = {
        'admin': {
            'uri': swift_uri,
            'port': swift_port,
            'protocol': swift_proto,
            'host': swift_host,
        },
    }
    mp['endpoints']['public'] = dict(mp['endpoints']['admin'])
    mp['endpoints']['internal'] = dict(mp['endpoints']['public'])

    return mp
<commit_msg>Forget import<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4

#    Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from anvil import log
from anvil import utils

LOG = log.getLogger(__name__)

def get_shared_params(cfg):
    mp = dict()

    host_ip = cfg.get('host', 'ip')
    mp['service_host'] = host_ip

    # Components of the various endpoints
    swift_host = cfg.getdefaulted('swift', 'swift_host', host_ip)
    swift_port = cfg.getdefaulted('swift', 'swift_port', '8080')
    swift_proto = cfg.getdefaulted('swift', 'swift_protocol', 'http')
    swift_uri = utils.make_url(swift_proto, swift_host, swift_port)
    mp['endpoints'] = {
        'admin': {
            'uri': swift_uri,
            'port': swift_port,
            'protocol': swift_proto,
            'host': swift_host,
        },
    }
    mp['endpoints']['public'] = dict(mp['endpoints']['admin'])
    mp['endpoints']['internal'] = dict(mp['endpoints']['public'])

    return mp
<|endoftext|>


<commit_before>#
#  Copyright (C) 2015-2020 by Last Run Contributors.
#
#  This file is part of Arena of Titans.
#
#  Arena of Titans is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Affero General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Arena of Titans is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Affero General Public License for more details.
#
#  You should have received a copy of the GNU Affero General Public License
#  along with Arena of Titans. If not, see <http://www.gnu.org/licenses/>.
#

import dataclasses
import math
from enum import Enum

from aot.game import Player
from aot.game.board import Board, Square
from aot.game.cards import Card
from aot.game.trumps import Power
from aot.game.trumps.effects import TrumpEffect

from ..config import config
from ..utils import get_time
from .utils import RequestTypes

def get_global_game_message(game):
    return {
        "rt": RequestTypes.GAME_UPDATED,
        "request": get_global_game_state(game),
    }

def get_global_game_state(game):
    return {
        "id": game.game_id,
        "actions": game.actions,
        "board": game.board,
        "is_over": game.is_over,
        "current_player_index": game.active_player.index,
        "nb_turns": game.nb_turns,
        "players": {player.index: _get_public_player_state(player) for player in game.players},
        "winners": game.winners,
    }

def _get_public_player_state(player):
    return {
        "active_trumps": player.trump_effects,
        "square": player.current_square,
        "name": player.name,
        "index": player.index,
        "hero": player.hero,
        "is_visible": player.is_visible,
        "can_pawn_be_selected": player.can_pawn_be_selected,
    }

def get_private_player_messages_by_ids(game):
    messages = {}

    for player in game.players:
        if player is not None:
            messages[player.id] = [get_private_player_message(game, player)]

    return messages

def get_private_player_message(game, player):
    return {
        "rt": RequestTypes.PLAYER_UPDATED,
        "request": get_private_player_state(game, player),
    }

def get_private_player_state(game, player):
    # Since between the request arrives (game.active_player.turn_start_time) and the time we
    # get here some time has passed. Which means, the elapsed time sent to the frontend could
    # be greater than 0 at the beginning of a turn.
    elapsed_time = get_time() - game.active_player.turn_start_time
    if elapsed_time < config["api"]["min_elapsed_time_to_consider"]:
        elapsed_time = 0

    return {
        "name": player.name,
        "index": player.index,
        "id": player.id,
        "available_trumps": player.available_trumps,
        "hero": player.hero,
        "your_turn": player.id == game.active_player.id,
        "on_last_line": player.on_last_line,
        "has_won": player.has_won,
        "rank": player.rank,
        "hand": [
            {"name": card.name, "color": card.color, "description": card.description}
            for card in player.hand
        ],
        "active_trumps": player.trump_effects,
        "trump_target_indexes": [
            player.index for player in game.players if player and player.can_be_targeted_by_trumps
        ],
        "has_remaining_moves_to_play": player.has_remaining_moves_to_play,
        "trumps_statuses": player.trumps_statuses,
        "can_power_be_played": player.can_power_be_played,
        "gauge_value": player.gauge.value,
        "elapsed_time": elapsed_time,
        "power": player.power,
        "special_action": player.name_next_special_action,
    }

def to_json(python_object):  # noqa: C901 too complex
    if isinstance(python_object, Enum):
        return python_object.value
    elif isinstance(python_object, Square):
        return {
            "x": python_object.x,
            "y": python_object.y,
            "color": python_object.color,
        }
    elif isinstance(python_object, Board):
        return {"updated_squares": python_object.updated_squares}
    elif isinstance(python_object, TrumpEffect):
        data = {
            "duration": python_object.duration if not math.isinf(python_object.duration) else None,
            "name": python_object.name,
            "color": python_object.color,
            "effect_type": python_object.effect_type,
        }
        return data
    elif isinstance(python_object, (set, frozenset)):
        return [to_json(element) for element in python_object]
    elif isinstance(python_object, Player):
        return {
            "name": python_object.name,
            "index": python_object.index,
        }
    elif isinstance(python_object, Card):
        return {
            "name": python_object.name,
            "color": python_object.color,
        }
    elif isinstance(python_object, type):
        return python_object.__name__
    elif dataclasses.is_dataclass(python_object):
        # Our dataclasses may hold a reference to a class which we can't serialize into JSON.
        trump_like = {
            key: value
            for key, value in dataclasses.asdict(python_object).items()
            if not isinstance(value, type)
        }
        if isinstance(trump_like.get("trump_args"), dict):
            trump_like = {
                **trump_like,
                **trump_like["trump_args"],
            }
            del trump_like["trump_args"]
        if isinstance(python_object, Power):
            trump_like["is_power"] = True
            trump_like["passive"] = python_object.passive

        return trump_like

    # Normally, this is unreachable
    raise TypeError(str(python_object) + " is not JSON serializable")  # pragma: no cover
<commit_msg>fix(serializers): make sure we don't serialize class in API messages<commit_after>#
#  Copyright (C) 2015-2020 by Last Run Contributors.
#
#  This file is part of Arena of Titans.
#
#  Arena of Titans is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Affero General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Arena of Titans is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Affero General Public License for more details.
#
#  You should have received a copy of the GNU Affero General Public License
#  along with Arena of Titans. If not, see <http://www.gnu.org/licenses/>.
#

import dataclasses
import math
from enum import Enum

from aot.game import Player
from aot.game.board import Board, Square
from aot.game.cards import Card
from aot.game.trumps import Power
from aot.game.trumps.effects import TrumpEffect

from ..config import config
from ..utils import get_time
from .utils import RequestTypes

def get_global_game_message(game):
    return {
        "rt": RequestTypes.GAME_UPDATED,
        "request": get_global_game_state(game),
    }

def get_global_game_state(game):
    return {
        "id": game.game_id,
        "actions": game.actions,
        "board": game.board,
        "is_over": game.is_over,
        "current_player_index": game.active_player.index,
        "nb_turns": game.nb_turns,
        "players": {player.index: _get_public_player_state(player) for player in game.players},
        "winners": game.winners,
    }

def _get_public_player_state(player):
    return {
        "active_trumps": player.trump_effects,
        "square": player.current_square,
        "name": player.name,
        "index": player.index,
        "hero": player.hero,
        "is_visible": player.is_visible,
        "can_pawn_be_selected": player.can_pawn_be_selected,
    }

def get_private_player_messages_by_ids(game):
    messages = {}

    for player in game.players:
        if player is not None:
            messages[player.id] = [get_private_player_message(game, player)]

    return messages

def get_private_player_message(game, player):
    return {
        "rt": RequestTypes.PLAYER_UPDATED,
        "request": get_private_player_state(game, player),
    }

def get_private_player_state(game, player):
    # Since between the request arrives (game.active_player.turn_start_time) and the time we
    # get here some time has passed. Which means, the elapsed time sent to the frontend could
    # be greater than 0 at the beginning of a turn.
    elapsed_time = get_time() - game.active_player.turn_start_time
    if elapsed_time < config["api"]["min_elapsed_time_to_consider"]:
        elapsed_time = 0

    return {
        "name": player.name,
        "index": player.index,
        "id": player.id,
        "available_trumps": player.available_trumps,
        "hero": player.hero,
        "your_turn": player.id == game.active_player.id,
        "on_last_line": player.on_last_line,
        "has_won": player.has_won,
        "rank": player.rank,
        "hand": [
            {"name": card.name, "color": card.color, "description": card.description}
            for card in player.hand
        ],
        "active_trumps": player.trump_effects,
        "trump_target_indexes": [
            player.index for player in game.players if player and player.can_be_targeted_by_trumps
        ],
        "has_remaining_moves_to_play": player.has_remaining_moves_to_play,
        "trumps_statuses": player.trumps_statuses,
        "can_power_be_played": player.can_power_be_played,
        "gauge_value": player.gauge.value,
        "elapsed_time": elapsed_time,
        "power": player.power,
        "special_action": player.name_next_special_action,
    }

def to_json(python_object):  # noqa: C901 too complex
    if isinstance(python_object, Enum):
        return python_object.value
    elif isinstance(python_object, Square):
        return {
            "x": python_object.x,
            "y": python_object.y,
            "color": python_object.color,
        }
    elif isinstance(python_object, Board):
        return {"updated_squares": python_object.updated_squares}
    elif isinstance(python_object, TrumpEffect):
        data = {
            "duration": python_object.duration if not math.isinf(python_object.duration) else None,
            "name": python_object.name,
            "color": python_object.color,
            "effect_type": python_object.effect_type,
        }
        return data
    elif isinstance(python_object, (set, frozenset)):
        return [to_json(element) for element in python_object]
    elif isinstance(python_object, Player):
        return {
            "name": python_object.name,
            "index": python_object.index,
        }
    elif isinstance(python_object, Card):
        return {
            "name": python_object.name,
            "color": python_object.color,
        }
    elif dataclasses.is_dataclass(python_object) and not isinstance(python_object, type):
        # Our dataclasses may hold a reference to a class which we can't serialize into JSON.
        trump_like = {
            key: _remove_class_references(value)
            for key, value in dataclasses.asdict(python_object).items()
            if not isinstance(value, type)
        }
        if isinstance(trump_like.get("trump_args"), dict):
            trump_like = {
                **trump_like,
                **trump_like["trump_args"],
            }
            del trump_like["trump_args"]
        if isinstance(python_object, Power):
            trump_like["is_power"] = True
            trump_like["passive"] = python_object.passive

        return trump_like

    # Normally, this is unreachable
    raise TypeError(str(python_object) + " is not JSON serializable")  # pragma: no cover

def _remove_class_references(data):
    if not isinstance(data, dict):
        return data

    return {
        key: _remove_class_references(value)
        for key, value in data.items()
        if not isinstance(value, type)
    }
<|endoftext|>


<commit_before>from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
<commit_msg>Revert "Trimmed init"<commit_after>from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ['celery_app']
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# manila documentation build configuration file, created by
# sphinx-quickstart on Sat May  7 13:35:27 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import os
import subprocess
import sys
import warnings

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../../'))
sys.path.insert(0, os.path.abspath('../'))
sys.path.insert(0, os.path.abspath('./'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'os_api_ref',
    'oslosphinx',
]

# Add any paths that contain templates here, relative to this directory.
# templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Shared File Systems API Reference'
copyright = u'2010-present, OpenStack Foundation'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
from manila.version import version_info
# The full version, including alpha/beta/rc tags.
release = version_info.release_string()
# The short X.Y version.
version = version_info.version_string()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
# language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = False

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
# html_theme = 'alabaster'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
# html_title = u'Shared File Systems API Reference v2'

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None

# The name of an image file (relative to this directory) to use as a favicon of
# the docs.  This file should be a Windows icon file (.ico) being 16x16 or
# 32x32 pixels large.
# html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
git_cmd = ["git", "log", "--pretty=format:'%ad, commit %h'", "--date=local",
           "-n1"]
try:
    html_last_updated_fmt = subprocess.Popen(
        git_cmd, stdout=subprocess.PIPE).communicate()[0]
except Exception:
    warnings.warn('Cannot get last updated time from git repository. '
                  'Not setting "html_last_updated_fmt".')

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}

# If false, no module index is generated.
# html_domain_indices = True

# If false, no index is generated.
# html_use_index = True

# If true, the index is split into individual pages for each letter.
# html_split_index = False

# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
# html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
# html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = 'maniladoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    # 'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    # 'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    # 'preamble': '',

    # Latex figure (float) alignment
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'manila.tex',
     u'OpenStack Shared File Systems API Documentation',
     u'OpenStack Foundation', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
# latex_appendices = []

# If false, no module index is generated.
# latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'manila', u'OpenStack Shared File Systems API Documentation',
     u'Openstack Foundation', 1)
]

# If true, show URL addresses after external links.
# man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'Manila', u'OpenStack Shared File Systems API Documentation',
     u'OpenStack Foundation', 'Manila', 'OpenStack Shared File Systems',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
# texinfo_appendices = []

# If false, no module index is generated.
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
<commit_msg>Get ready for os-api-ref sphinx theme change<commit_after># -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# manila documentation build configuration file, created by
# sphinx-quickstart on Sat May  7 13:35:27 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import os
import subprocess
import sys
import warnings

# TODO(Graham Hayes): Remove the following block of code when os-api-ref is
# using openstackdocstheme

import os_api_ref

if getattr(os_api_ref, 'THEME', 'olsosphinx') == 'openstackdocstheme':
    # We are on the new version with openstackdocstheme support

    extensions = [
        'os_api_ref',
    ]

    import openstackdocstheme  # noqa

    html_theme = 'openstackdocs'
    html_theme_path = [openstackdocstheme.get_html_theme_path()]
    html_theme_options = {
        "sidebar_mode": "toc",
    }

else:
    # We are on the old version without openstackdocstheme support

    extensions = [
        'os_api_ref',
        'oslosphinx',
    ]

# End temporary block

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../../'))
sys.path.insert(0, os.path.abspath('../'))
sys.path.insert(0, os.path.abspath('./'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.

# Add any paths that contain templates here, relative to this directory.
# templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Shared File Systems API Reference'
copyright = u'2010-present, OpenStack Foundation'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
from manila.version import version_info
# The full version, including alpha/beta/rc tags.
release = version_info.release_string()
# The short X.Y version.
version = version_info.version_string()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
# language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = False

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
# html_theme = 'alabaster'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
# html_title = u'Shared File Systems API Reference v2'

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None

# The name of an image file (relative to this directory) to use as a favicon of
# the docs.  This file should be a Windows icon file (.ico) being 16x16 or
# 32x32 pixels large.
# html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
git_cmd = ["git", "log", "--pretty=format:'%ad, commit %h'", "--date=local",
           "-n1"]
try:
    html_last_updated_fmt = subprocess.Popen(
        git_cmd, stdout=subprocess.PIPE).communicate()[0]
except Exception:
    warnings.warn('Cannot get last updated time from git repository. '
                  'Not setting "html_last_updated_fmt".')

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}

# If false, no module index is generated.
# html_domain_indices = True

# If false, no index is generated.
# html_use_index = True

# If true, the index is split into individual pages for each letter.
# html_split_index = False

# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
# html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
# html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = 'maniladoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    # 'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    # 'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    # 'preamble': '',

    # Latex figure (float) alignment
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'manila.tex',
     u'OpenStack Shared File Systems API Documentation',
     u'OpenStack Foundation', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
# latex_appendices = []

# If false, no module index is generated.
# latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'manila', u'OpenStack Shared File Systems API Documentation',
     u'Openstack Foundation', 1)
]

# If true, show URL addresses after external links.
# man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'Manila', u'OpenStack Shared File Systems API Documentation',
     u'OpenStack Foundation', 'Manila', 'OpenStack Shared File Systems',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
# texinfo_appendices = []

# If false, no module index is generated.
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
<|endoftext|>