def setUp(self):
     self.graph1 = createGraphFromString(
         "#########\n#[email protected]#\n#########\n")
     self.graph2 = createGraphFromString(
         "########################\n#[email protected].#\n######################.#\n#d.....................#\n########################\n"
     )
     self.graph3 = createGraphFromString(
         "########################\n#...............b.C.D.f#\n#.######################\n#[email protected]#\n########################\n"
     )
     self.graph4 = createGraphFromString(
         "#################\n#i.G..c...e..H.p#\n########.########\n#j.A..b...f..D.o#\n########@########\n#k.E..a...g..B.n#\n########.#########l.F..d...h..C.m#\n#################\n"
     )
     self.graph5 = createGraphFromString(
         "########################\n#@..............ac.GI.b#\n###d#e#f################\n###A#B#C################\n###g#h#i################\n########################\n"
     )
     self.instance1 = Instance(self.graph1)
     self.instance1.updateTokens()
     self.instance2 = Instance(self.graph2)
     self.instance2.updateTokens()
     self.instance3 = Instance(self.graph3)
     self.instance3.updateTokens()
     self.instance4 = Instance(self.graph4)
     self.instance4.updateTokens()
     self.instance5 = Instance(self.graph5)
     self.instance5.updateTokens()
示例#2
0
def senToInstan(S, ListInstance):
    sentence = S
    e1List = sentence.e1_List
    e2List = sentence.e2_List
    for e1 in e1List:
        for e2 in e2List:
            f = 0
            # e1在前面
            if e1[1] <= e2[1]:
                for word in sentence.segSentence2[e1[1] + 1:e2[1]]:
                    # 判断了这两个词是不是在一句话中
                    if word in ['.', '。', ';', ';']:
                        f = 1
                        break
                if f == 0:
                    # 添加一个实例
                    instance = Instance(S, e1, e2, flag=0)
                    ListInstance.append(instance)
            # e2在后面
            if e1[1] > e2[1]:
                for word in sentence.segSentence2[e2[1] + 1:e1[1]]:
                    if word in ['.', '。', ';', ';']:
                        f = 1
                        break
                if f == 0:
                    instance = Instance(S, e1, e2, flag=1)
                    ListInstance.append(instance)
    return ListInstance
def parametrized(instance_file, algorithm):
    instances = {}
    solutions = {}
    relative_errors = []

    for instance_line in instance_file:
        instance = Instance(instance_line.rstrip('\n'))
        instances.update({instance.get_id(): instance})

    print("knapsack_id,algorithm,no_items,price,time_ms")

    # backpack_size = next(iter(solutions.values())).get_no_items()
    for id_inst, instance in instances.items():
        if algorithm == "heuristic":
            computed = instance.with_heuristic()
        elif algorithm == "branch_bound":
            method = BranchBound()
            computed = method.solve(instance)
        elif algorithm == "genetic":
            method = Genetic()
            computed = method.solve(instance)
        elif algorithm == "dynamic":
            computed = instance.dynamic()
        elif algorithm == "fptas":
            computed = instance.fptas(75)
        elif algorithm == "brute_force":
            computed = instance.brute_force()
        time = measured_time[-1]['time']
        print(
            f'{id_inst},{algorithm},{instance.no_items},{computed.get_cost()},{time}'
        )
示例#4
0
def init(instanceDir, file):
    """ Setup function. Calls the Instance Constructor.

        Args:
            instanceDir    (Dir)                  - The Directory containig the instance files to use to build the instance objects.
            file           (Str)                  - The file to use.

        Returns:
            instance        (Instance.Instance)     - The instance object built

        Globals:
            None

        Called By:
            Main.init()

        Calls:
            Constructor
    """
    instance = Instance.Instance()
    filepath = instanceDir + "\\" + file
    with open(filepath, 'r') as inst:
        Constructor(inst, instance)

    inst.close()
    return instance
示例#5
0
def initLargeApp():
    global instances
    instances = []
    instances.append(Instance.Instance('C1.Medium Spot',      252, 60, 0.00046, True))
    instances.append(Instance.Instance('C1.XLarge Spot',      100,  28, 0.00186, True))
    instances.append(Instance.Instance('C1.Medium On-Demand', 252, 60, 0.00241, False))
    instances.append(Instance.Instance('C1.XLarge On-Demand', 100,  28, 0.00967, False))
    #TODO adjust number of slaves
    # setSlaves(500)

    global shortageMultiplier
    shortageMultiplier = 16.0

    global S3
    S3 = Storage.Storage(0,8) # copies per GB
    
    global FastestOnDemandRate
    FastestOnDemandRate = 500/29
    global CheapestOnDemandRate
    CheapestOnDemandRate = 500/61
    global FastestSpotRate
    FastestSpotRate = FastestOnDemandRate/2
示例#6
0
def initFirefox():
    global instances
    instances = []
    instances.append(Instance.Instance('C1.Medium Spot',      63, 15, 0.00046, True))
    instances.append(Instance.Instance('C1.XLarge Spot',      25,  7, 0.00186, True))
    instances.append(Instance.Instance('C1.Medium On-Demand', 63, 15, 0.00241, False))
    instances.append(Instance.Instance('C1.XLarge On-Demand', 25,  7, 0.00967, False))
    #TODO adjust number of slaves
    # setSlaves(500)


    global shortageMultiplier
    shortageMultiplier = 4.0

    global S3
    S3 = Storage.Storage(0,33) # copies per GB
    
    global FastestOnDemandRate
    FastestOnDemandRate = 500/8
    global CheapestOnDemandRate
    CheapestOnDemandRate = 500/15
    global FastestSpotRate
    FastestSpotRate = FastestOnDemandRate/2
示例#7
0
def parse_dimacs(instance_file):
    instance = Instance()
    current = []
    read = 0
    for instance_line in instance_file:
        if instance.variables == -1 or instance.weights == []:
            if instance_line[0] == 'c':
                continue
            elif instance_line[0] == 'p':
                tokens = instance_line.split()
                if len(tokens) != 4:
                    raise BadDIMACSFormatError(f"Not enough parameters in problem line, found {len(tokens)}") 

                if tokens[1] != "cnf":
                    raise BadDIMACSFormatError(f"Not cnf format, is {tokens[0]}") 

                instance.variables = int(tokens[2])
                instance.clauses = int(tokens[3])
                continue
            elif instance_line[0] == 'w':
                tokens = instance_line.split()

                for token in tokens[1:]:
                    # print(token)
                    instance.weights.append(int(token))
                continue
            else:
                raise BadDIMACSFormatError(f"Invalid start of line char: {instance_line[0]}")


        end = False
        tokens = instance_line.split()
        for token in tokens:

            if token == "0":
                end = True
                break
            current.append(int(token))


        if end:
            instance.formula.append(current)
            current = []

            read += 1
            if read >= instance.clauses:
                break


    return instance
def genetic(instance_file,
            xover_probability=0.4,
            mutation_probability=0.1,
            elitism_count=10,
            tournament_count=16,
            tournament_pool_size=2,
            generations=1000):
    instances = {}

    # print("xover_probability", xover_probability,
    #     "mutation_probability", mutation_probability,
    #     "elitism_count", elitism_count,
    #     "tournament_count", tournament_count,
    #     "tournament_pool_size", tournament_pool_size,
    #     "generations", generations)

    for instance_line in instance_file:
        instance = Instance(instance_line.rstrip('\n'))
        instances.update({instance.get_id(): instance})

    for id_inst, instance in instances.items():

        method = Genetic(xover_probability=xover_probability,
                         mutation_probability=mutation_probability,
                         elitism_count=elitism_count,
                         tournament_count=tournament_count,
                         tournament_pool_size=tournament_pool_size,
                         generations=generations,
                         verbose=True)
        computed = method.solve(instance)
        # print(f'{id_inst},genetic,{instance.no_items},{computed.get_cost()}')
        # print ("ge:", computed)

        method = BranchBound()
        computed = method.solve(instance)
        # print(f'{id_inst},branch,{instance.no_items},{computed.get_cost()}')
        # print ("Bb:", computed)
        # print("-----")

    pass
示例#9
0
        {'id':3,'price':80,'inventory':40,'initial_inventory':40,'adjusted_initial_inventory':40,'extra_inventory':0,'inventory_in_transit':0},#200
        {'id':4,'price':70,'inventory':50,'initial_inventory':50,'adjusted_initial_inventory':50,'extra_inventory':0,'inventory_in_transit':0},#300
        #{'id':5,'price':60,'inventory':50,'initial_inventory':50,'adjusted_initial_inventory':50,'extra_inventory':0,'inventory_in_transit':0},
        #{'id':6,'price':50,'inventory':30,'initial_inventory':30,'adjusted_initial_inventory':30,'extra_inventory':0,'inventory_in_transit':0},
        #{'id':7,'price':40,'inventory':20,'initial_inventory':20,'adjusted_initial_inventory':20,'extra_inventory':0,'inventory_in_transit':0},
        #{'id':8,'price':30,'inventory':15,'initial_inventory':15,'adjusted_initial_inventory':15,'extra_inventory':0,'inventory_in_transit':0},
        #{'id':9,'price':20,'inventory':15,'initial_inventory':15,'adjusted_initial_inventory':15,'extra_inventory':0,'inventory_in_transit':0},
        #{'id':10,'price':10,'inventory':20,'initial_inventory':20,'adjusted_initial_inventory':20,'extra_inventory':0,'inventory_in_transit':0},
        ]
N_ITEM = len(ITEM)

CUSTOMER = [{'preference': [0] + list(random.normal(CUSTOMER_MEAN[k],CUSTOMER_SIGMA[k],size=N_ITEM)),'id':k }
            for k in range(CUSTOMER_NUM)            
            ]

instance = Instance(ITEM,CUSTOMER)

# Input parameters
T = 100


instance.Run(T,**SETTING)


#--- 用相同的customer sequence 跑一遍
SETTING['run_again'] = True

SETTING['IB_function_type'] = 'exponential'
instance.Run(T,**SETTING)

SETTING['IB_function_type'] = 'linear'
示例#10
0
# listfile = ['10hk48.clt']
# listfile = ['6i300.clt']
# listfile = ['10eil76.clt']
def secondsToStr(t):
    return "%d:%02d:%02d.%03d" % \
        reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
            [(t*1000,),1000,60,60])


for file in listfile:
    seeds = range(0, 30)
    for seed in seeds:
        start_time = time.time()

        instance = Instance(file, seed)

        if not instance.use:
            continue
        print(instance.name)
        population = instance.init(pop)
        result_file = open(instance.resultname, 'w')
        result_file.write("Generation \t" + instance.name + '\n')
        for x in range(gen):
            teacher = min(population, key=attrgetter('fitness'))
            #write to file
            result_file.write(str(x) + ' \t' + str(teacher.fitness) + '\n')
            diff = np.random.rand() * (teacher.subjects - np.random.randint(
                1, 3) * np.mean([x.subjects for x in population], axis=0))
            # buoc 1
            for y in range(pop):
示例#11
0
objects = [Entry(np.array([5.0,5.0]), np.array([4,4])), Obstacle(np.array([20.0,10.0]), np.array([10, 5])), Obstacle(np.array([60.0,60.0]), np.array([10, 10])), Obstacle(np.array([0.0,0.0]), np.array([2, 80])), Obstacle(np.array([0.0,0.0]), np.array([80, 2])), Obstacle(np.array([78.0,0.0]), np.array([2, 80])), Obstacle(np.array([0.0, 78.0]), np.array([80, 2])), Exit(np.array([76.0, 76.0]), np.array([2, 2]))]
objects.append(Obstacle(np.array([50.0,25.0]), np.array([20, 5])))
objects.append(Exit(np.array([75.0,3.0]), np.array([2, 3])))
objects.append(Entry(np.array([5.0,70.0]), np.array([4,4])))
objects.append(Entry(np.array([35.0,70.0]), np.array([4,4])))
objects.append(Obstacle(np.array([50.0,50.0]), np.array([10, 20])))
objects.append(Obstacle(np.array([20.0,25.0]), np.array([3, 18])))
objects.append(Obstacle(np.array([50.0,25.0]), np.array([5, 24])))
'''
paths = load_path("paths.txt")

F = []

for path in paths:
    F.append(Folower(path))
setup = Setup(size, margin, objects, people)

for k in range(2, 3):
    instance = Instance(setup, 1, k)
    instance.people[0].pos = np.copy(F[k].pos)
    instance.people[0].des_pos = np.copy(F[k].path[-1])
    instance.people[0].direction = np.copy(F[k].direction)
    instance.people[0].vel = np.copy(F[k].vel)
    instance.people[0].des_speed = np.copy(np.linalg.norm(F[k].vel))

    instance.people[0].rad = np.copy(F[k].rad)

    instance.agents = F

    instance.init_show()
示例#12
0
#objects = [Entry(np.array([3.0,3.0]), np.array([4,4])), Obstacle(np.array([30.0,10.0]), np.array([20, 20])), Obstacle(np.array([60.0,60.0]), np.array([10, 20])), Obstacle(np.array([0.0,0.0]), np.array([2, 100])), Obstacle(np.array([0.0,0.0]), np.array([100, 2])), Obstacle(np.array([98.0,0.0]), np.array([2, 100])), Obstacle(np.array([0.0, 98.0]), np.array([100, 2])), Exit(np.array([96.0, 96.0]), np.array([2, 2]))]

in_terface = In_Terface()
in_terface.initialize_interface()
#in_terface.initialize_silent_interface()

saved_state = in_terface.get_state()
size = saved_state.screen_size // 5
objects = saved_state.objects
'''
size = np.array([80,80])
margin, people = 5, []


objects = [Entry(np.array([5.0,5.0]), np.array([4,4])), Obstacle(np.array([20.0,10.0]), np.array([10, 5])), Obstacle(np.array([60.0,60.0]), np.array([10, 10])), Obstacle(np.array([0.0,0.0]), np.array([2, 80])), Obstacle(np.array([0.0,0.0]), np.array([80, 2])), Obstacle(np.array([78.0,0.0]), np.array([2, 80])), Obstacle(np.array([0.0, 78.0]), np.array([80, 2])), Exit(np.array([76.0, 76.0]), np.array([2, 2]))]
objects.append(Obstacle(np.array([50.0,25.0]), np.array([20, 5])))
objects.append(Exit(np.array([75.0,3.0]), np.array([2, 3])))
objects.append(Entry(np.array([5.0,70.0]), np.array([4,4])))
objects.append(Entry(np.array([35.0,70.0]), np.array([4,4])))
objects.append(Obstacle(np.array([50.0,50.0]), np.array([10, 20])))
objects.append(Obstacle(np.array([20.0,25.0]), np.array([3, 18])))
objects.append(Obstacle(np.array([50.0,25.0]), np.array([5, 24])))
'''

setup = Setup(size, margin, objects, people)

instance = Instance(setup)

instance.init_show()
iam = boto3.resource('iam')
role = None
try:
    role = Iam_Role.Iam_Role(iam.Role('cs5250-EC2-backend-role'))
    check_iam_role(role)
except:
    print('Error retrieving IAM Role')

ec2 = boto3.resource('ec2')
instances_from_aws = ec2.instances.all()
instances = list()

for instance in instances_from_aws:
    vpc_id = instance.vpc_id
    instances.append(Instance.Instance(instance))
try:
    vpc = VPC.VPC(vpc_id)
    print()
    check_vpc(vpc)
except:
    print(f'Error retrieving VPC {vpc_id}')

for instance in instances:
    instance.subnet = vpc.get_subnet_name(instance.subnet)

print()
check_instances(instances)

if len(argv) > 1 and argv[1] == '-p':
    if not role == None:
示例#14
0
文件: numeric.py 项目: evyadai/GSR
@author: Evyatar
"""

import time
from math import *
import numpy as np
from scipy import optimize
from Instance import *


def const1(x):
    return 1.0


def slope1(x):
    return x


csr = Instance(slope1, const1, 1.0)
detStr = csr.optDetStr()
if detStr[0] == float("Inf"):
    print "The optimal deterministic strategy never switch and has a competitive ratio of", detStr[
        1]
elif detStr[1] == 0.0:
    print "The optimal deterministic strategy start at buy state and has a competitive ratio of", detStr[
        1]
else:
    print "The optimal deterministic strategy switch at time", detStr[
        0], "and has a competitive ratio of", detStr[1]
示例#15
0
async def on_message(text):
    """Handles all commands the bot considers valid. Scans all messages, so long as they are not from bots, to see if those messages start with a valid command."""
    report = ""  # report is usually what the bot sends in response to valid commands, and, in case a game is active, it is what the bot write to that game's log file.
    text.content = text.content.lower(
    )  # for ease of use, all commands are lowercase, and all messages scanned are converted to lowercase.
    current = text.channel.id
    exist = False
    heldGame = None
    botSpoke = False
    if not text.author.bot:
        for i in range(len(games)):
            if current == games[i].getChannel():
                exist = True
                print(
                    str(current) + " " + str(datetime.now())[:-5] + " " +
                    text.author.name + ": " + text.content
                )  # I disabled printing every message because it was just too much. Now it only prints if a game is active.
                heldGame = games[i]
                break

        if text.content.startswith('!setup'):
            print("Running setup...")
            botSpoke = True
            """Run this command once, after you add the bot the your server. It will handle all role and emoji creation, and set the bot's avatar.
            Please avoid running this command more than once, as doing so will create duplicate emojis. If for whatever reason you have to do so, that's fine, just be prepared to delete those emojis.'
            """
            report = "This command is only usable by server admins!"
            if text.author.guild_permissions.administrator:  # Bot setup requires admin perms.
                await text.channel.send("Starting setup...")
                report = "Successfully set up the bot!"

                # This block handles role creation. The bot requires these roles to function, so it will make them when you run !setup.
                willHoist = True  # Hoist makes it so that a given role is displayed separately on the sidebar. If for some reason you don't want teams displayed separately, set this to False.
                roles = {
                    "Reader": 0x01ffdd,
                    "Team red": 0xf70a0a,
                    "Team blue": 0x009ef7,
                    "Team green": 0x7bf70b,
                    "Team orange": 0xff6000,
                    "Team yellow": 0xfeed0e,
                    "Team purple": 0xb40eed
                }
                for x, y in roles.items():
                    if not get(text.guild.roles, name=x):
                        await text.guild.create_role(name=x,
                                                     colour=discord.Colour(y),
                                                     hoist=willHoist)
                        print("Created " + x + ".")
                print("Roles live!")

                # This block creates the emojis the bot accepts for points and buzzes. Credit for these wonderful emojis goes to Theresa Nyowheoma, President of Quiz Bowl at NYU, 2020-2021.
                try:
                    with open("templates/emoji/buzz.png", "rb") as buzzIMG:
                        img = buzzIMG.read()
                        buzz = await text.guild.create_custom_emoji(
                            name='buzz', image=img)
                    with open("templates/emoji/neg.png", "rb") as negIMG:
                        img = negIMG.read()
                        neg = await text.guild.create_custom_emoji(name='neg',
                                                                   image=img)
                    with open("templates/emoji/ten.png", "rb") as tenIMG:
                        img = tenIMG.read()
                        ten = await text.guild.create_custom_emoji(name='ten',
                                                                   image=img)
                    with open("templates/emoji/power.png", "rb") as powerIMG:
                        img = powerIMG.read()
                        power = await text.guild.create_custom_emoji(
                            name='power', image=img)
                    print("Emoji live!")
                    report += " Team roles now exist, as do the following emoji: " + str(
                        buzz) + ", " + str(neg) + ", " + str(ten) + ", " + str(
                            power) + "."
                    with open("templates/pfp.png", "rb") as pfp:
                        pic = pfp.read()
                        try:
                            await client.user.edit(
                                avatar=pic
                            )  # Running !setup too many times will cause the Discord API to deny API calls that try to change the profile picture.
                            print("Avatar live!")
                        except discord.HTTPException:  # In case of the above issue:
                            print("Avatar failed to update!")
                            report += " Failed to update the Bot's profile picture."
                except FileNotFoundError:
                    report = "Failed to load images for emoji or profile picture! Check your directory structure."

            await text.channel.send(report)
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if text.content.startswith('!summon') or text.content.startswith(
                '!call'):
            """Mentions everyone in the server, pinging them and informing them that it is time for practice."""
            print("calling summon")
            botSpoke = True
            report = "This command is only usable by server admins!"
            if text.author.guild_permissions.administrator:  # this makes sure people can't just ping everyone in the server whenever they want. Only admins can do that.
                report = summon(
                ) if verbosePings else "@everyone it's time for Quiz Bowl practice."  # For the full list of summon messages, check Summon.py.
            await text.channel.send(report)
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if text.content.startswith('!start') or text.content.startswith(
                '!begin') or text.content.startswith('!read'):
            botSpoke = True
            print("calling start")
            if exist:
                report = "You already have an active game in this channel."
            else:
                role = get(
                    text.guild.roles, name='Reader'
                )  # The bot needs you to make a role called "Reader" in order to function.
                if role:
                    report = "Starting a new game. Reader is " + text.author.mention + "."
                    x = Instance(current, text.channel)
                    x.reader = text.author
                    print(x.getChannel())
                    await text.author.add_roles(role)
                    heldGame = x
                    with open(x.logFile, "a") as log:
                        log.write("Start of game in channel " + str(current) +
                                  " at " +
                                  datetime.now().strftime("%H:%M:%S") +
                                  ".\r\n\r\n")
                    with open(x.csvScore, "a") as score:
                        #score.write("TU#,Red Bonus,Blue Bonus,Green Bonus,Orange Bonus,Yellow Bonus,Purple Bonus,")
                        # Currently creates the scoresheet and does nothing else.
                        pass
                    games.append(x)
                else:
                    report = "You need to run !setup before you can start a game."
            await text.channel.send(report)
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if exist:  # These commands only fire if a game is active in the channel in which they are being run.
            if text.content.startswith('!newreader'):
                print("calling newreader")
                botSpoke = True
                target = text.content.split('@', 1)[1]
                target = target[1:-1] if target.startswith(
                    '!') else target[:-1]
                role = get(text.guild.roles, name='Reader')
                await heldGame.reader.remove_roles(role)
                newReader = await text.guild.fetch_member(target)
                heldGame.reader = newReader
                await newReader.add_roles(role)
                report = "Made " + newReader.mention + " the new reader."
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith('!end') or text.content.startswith(
                    '!stop'):
                print("calling end")
                botSpoke = True
                for i in range(len(games)):
                    if current == games[i].getChannel():
                        if text.author.id == games[
                                i].reader.id or text.author.guild_permissions.administrator:
                            #with open(games[i].csvScore) as score:
                            #body = score.readlines()
                            #subMems = body[0]
                            #newLine = "Total:," + str(games[i].redBonus) + "," + str(games[i].blueBonus) + "," + str(games[i].greenBonus) + "," + str(games[i].orangeBonus) + "," + str(games[i].yellowBonus) + "," + str(games[i].purpleBonus) + ","
                            #with open(games[i].csvScore, "a") as score:
                            #for x, y in games[i].scores.items():
                            #newLine += str(y) + ","
                            #score.write(newLine)
                            csvName = games[i].csvScore
                            games.pop(i)
                            report = "Ended the game active in this channel. Here is the scoresheet (I am rewriting all the code involving the scoresheet; it will be extremely inaccurate for some time. Scoresheets are currently empty)."
                            #report = "Ended the game active in this channel."
                            role = get(text.guild.roles, name='Reader')
                            await heldGame.reader.remove_roles(
                                role
                            )  # The Reader is stored as a Member object in heldGame, so any admin can end the game and the Reader role will be removed.
                            await text.channel.send(report)
                            await text.channel.send(file=discord.File(
                                csvName, filename="scoresheet.csv"))
                        else:
                            report = "You are not the reader or a server admin!"
                            await text.channel.send(report)
                        break
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return
            """
            # DEPRECATED until I fully implement scoresheets and figure out the issue with TUnum tracking.
            if text.content.startswith('!undo'):
                print("calling undo")
                botSpoke = True
                if text.author.id == heldGame.reader.id:
                    if heldGame.bonusMode:
                        report = "Finish your bonus first!"
                    else:
                        if heldGame.active:
                            report = "Assign TU points first!"
                        else:
                            if heldGame.TUnum == 0 and len(heldGame.scores) == 0:
                                report = "Nothing to undo."
                            else:
                                heldGame.undo()
                                report = "Undid last Tossup scorechange."
                else:
                    report = "You are not the reader!"
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content, heldGame, report, botSpoke)
                return
            """

            if text.content.startswith('!dead'):
                print("calling dead")
                botSpoke = True
                report = "You are not the reader!"
                if text.author.id == heldGame.reader.id:
                    heldGame.dead()
                    report = "TU goes dead. Moving on to TU #" + str(
                        heldGame.TUnum + 1) + "."
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith('!clear'):
                print("calling clear")
                botSpoke = True
                report = "You are not the reader!"
                if text.author.id == heldGame.reader.id:
                    heldGame.clear()
                    report = "Buzzers cleared, anyone can buzz."
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if isInt(text.content):  # Assigns points.
                print("calling points")
                print(text.content + " is an int")
                if text.content.startswith(
                        '<:neg:'
                ):  # This and the next two conditionals check to see if someone is using a valid emoji to assign points. While, to the user, an emoji looks like :emojiName:, to the bot it is also wrapped in <>.
                    text.content = "-5"
                elif text.content.startswith('<:ten:'):
                    text.content = "10"
                elif text.content.startswith('<:power:'):
                    text.content = "15"
                botSpoke = True
                report = "Null"  # if someone besides the reader types a number, this will do nothing
                if text.author.id == heldGame.reader.id:
                    if heldGame.bonusEnabled == False:
                        if heldGame.gain(int(text.content)):
                            report = "Awarded points. Moving on to TU #" + str(
                                heldGame.TUnum + 1) + "."
                            await text.channel.send(report)
                        else:
                            report = "No held buzzes."
                            while len(heldGame.buzzes) > 0:
                                if heldGame.canBuzz(heldGame.buzzes[0]):
                                    report = (
                                        heldGame.buzzes[0]
                                    ).mention + " buzzed. Pinging reader: " + str(
                                        heldGame.reader.mention)
                                    await text.channel.send(report)
                                    break
                                else:
                                    heldGame.buzzes.popleft(
                                    )  # Pop until we find someone who can buzz, or until the array of buzzes is empty.
                                    report = "Cannot buzz."
                    else:  # bonuses enabled
                        if heldGame.bonusMode == False:
                            storedMem = heldGame.buzzes[0]
                            if heldGame.gain(int(text.content)):
                                report = "Awarded TU points. "
                                getTeam = heldGame.inTeam(storedMem)
                                message = await text.channel.send(report)
                                if getTeam != None:
                                    report += "Bonus is for " + getTeam.mention + ". "
                                report += "Awaiting bonus points."
                                await asyncio.sleep(.1)
                                await message.edit(content=report)
                            else:
                                report = "No held buzzes."
                                while len(heldGame.buzzes) > 0:
                                    if heldGame.canBuzz(heldGame.buzzes[0]):
                                        report = (
                                            heldGame.buzzes[0]
                                        ).mention + " buzzed. Pinging reader: " + str(
                                            heldGame.reader.mention)
                                        await text.channel.send(report)
                                        break
                                    else:
                                        heldGame.buzzes.popleft(
                                        )  # Pop until we find someone who can buzz, or until the array of buzzes is empty.
                                        report = "Cannot buzz."
                                        # because I don't want to send a report here, I can't have the text.channel.send(report) at the end
                        else:  # bonusMode true
                            heldGame.bonusGain(int(text.content))
                            report = "Awarded bonus points. Moving on to TU #" + str(
                                heldGame.TUnum + 1) + "."
                            await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith('wd') or text.content.startswith(
                    '!wd') or text.content.startswith(
                        'withdraw') or text.content.startswith('!withdraw'):
                print("calling withdraw")
                botSpoke = True
                report = "Only the currently recognized player can withdraw."
                if heldGame.buzzes[0] == text.author:
                    heldGame.buzzes.popleft()
                    newBuzzed = deque()
                    while len(heldGame.buzzed) > 0:
                        if heldGame.buzzed[0] == text.author:
                            heldGame.buzzed.popleft()
                        else:
                            newBuzzed.append(heldGame.buzzed.popleft())
                    heldGame.buzzed = newBuzzed
                    report = "Withdrew " + text.author.mention + "'s buzz. "
                    while len(heldGame.buzzes) > 0:
                        if heldGame.canBuzz(heldGame.buzzes[0]):
                            report += (
                                heldGame.buzzes[0]
                            ).mention + " buzzed. Pinging reader: " + str(
                                heldGame.reader.mention)
                            break
                        else:
                            heldGame.buzzes.popleft()
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith(
                    '!bonusmode') or text.content.startswith('!btoggle'):
                """Toggles whether bonus mode is enabled. It is enabled by default."""
                print("calling bonusmode")
                botSpoke = True
                report = "You are not the reader!"
                if text.author.id == heldGame.reader.id or text.author.guild_permissions.administrator:
                    heldGame.bonusStop()
                    heldGame.bonusEnabled = not heldGame.bonusEnabled
                    report = "Enabled bonus mode." if heldGame.bonusEnabled else "Disabled bonus mode."
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith('!bstop'):
                """Ends current bonus round. Use this to kill a bonus without giving points. Only use if something has gone wrong and you need to kill a bonus immediately."""
                print("calling bstop")
                botSpoke = True
                report = "You are not the reader!"
                if text.author.id == heldGame.reader.id:
                    heldGame.bonusStop()
                    report = "Killed active bonus. Next TU."
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith('!score'):
                print("calling score")
                diction = {}
                botSpoke = True
                areTeams = False
                if len(heldGame.scores) == 0:
                    desc = "Score at start of game:"
                else:
                    desc = "Score after " + str(
                        heldGame.TUnum) + " completed TUs: "
                    #The following seven conditionals modify the scoreboard to include team scores, if those teams exist.
                    if heldGame.teamExist(heldGame.redTeam):
                        desc += "\r\nRed team: " + str(
                            heldGame.teamScore(heldGame.redTeam,
                                               heldGame.redBonus))
                        areTeams = True
                    if heldGame.teamExist(heldGame.blueTeam):
                        desc += "\r\nBlue team: " + str(
                            heldGame.teamScore(heldGame.blueTeam,
                                               heldGame.blueBonus))
                        areTeams = True
                    if heldGame.teamExist(heldGame.greenTeam):
                        desc += "\r\nGreen team: " + str(
                            heldGame.teamScore(heldGame.greenTeam,
                                               heldGame.greenBonus))
                        areTeams = True
                    if heldGame.teamExist(heldGame.orangeTeam):
                        desc += "\r\nOrange team: " + str(
                            heldGame.teamScore(heldGame.orangeTeam,
                                               heldGame.orangeBonus))
                        areTeams = True
                    if heldGame.teamExist(heldGame.yellowTeam):
                        desc += "\r\nYellow team: " + str(
                            heldGame.teamScore(heldGame.yellowTeam,
                                               heldGame.yellowBonus))
                        areTeams = True
                    if heldGame.teamExist(heldGame.purpleTeam):
                        desc += "\r\nPurple team: " + str(
                            heldGame.teamScore(heldGame.purpleTeam,
                                               heldGame.purpleBonus))
                        areTeams = True
                    if areTeams:
                        desc += "\r\n\r\nIndividuals:"
                emb = discord.Embed(title="Score",
                                    description=desc,
                                    color=0x57068C)
                for x, y in heldGame.scores.items():
                    diction[
                        x.name if x.nick == None else x.
                        nick] = y  # Tries to display the Member's Discord nickname if possible, but if none exists, displays their username.
                sortedDict = OrderedDict(
                    sorted(diction.items(), key=itemgetter(1)))
                print(sortedDict)
                for i in range(len(sortedDict.items())):
                    tup = sortedDict.popitem()
                    emb.add_field(name=(str(i + 1) + ". " + tup[0]),
                                  value=str(tup[1]),
                                  inline=True)
                await text.channel.send(embed=emb)
                report = "Embedded score."
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if isBuzz(
                    text.content
            ):  # Uses the isBuzz() helper method to dermine if somene is buzzing
                print("calling buzz")
                botSpoke = True
                # This block handles all team assignment that was done before the game started.
                red = get(text.guild.roles, name='Team red')
                blue = get(text.guild.roles, name='Team blue')
                green = get(text.guild.roles, name='Team green')
                orange = get(text.guild.roles, name='Team orange')
                yellow = get(text.guild.roles, name='Team yellow')
                purple = get(text.guild.roles, name='Team purple')
                if red in text.author.roles and not text.author in heldGame.redTeam:
                    heldGame.redTeam.append(text.author)
                    print("Added " + text.author.name + " to red on buzz")
                elif blue in text.author.roles and not text.author in heldGame.blueTeam:
                    heldGame.blueTeam.append(text.author)
                    print("Added " + text.author.name + " to blue on buzz")
                elif green in text.author.roles and not text.author in heldGame.greenTeam:
                    heldGame.greenTeam.append(text.author)
                    print("Added " + text.author.name + " to green on buzz")
                elif orange in text.author.roles and not text.author in heldGame.orangeTeam:
                    heldGame.orangeTeam.append(text.author)
                    print("Added " + text.author.name + " to orange on buzz")
                elif yellow in text.author.roles and not text.author in heldGame.yellowTeam:
                    heldGame.yellowTeam.append(text.author)
                    print("Added " + text.author.name + " to yellow on buzz")
                elif purple in text.author.roles and not text.author in heldGame.purpleTeam:
                    heldGame.purpleTeam.append(text.author)
                    print("Added " + text.author.name + " to purple on buzz")
                if heldGame.bonusMode == False:
                    if heldGame.hasBuzzed(text.author):
                        print("You have already buzzed, " +
                              text.author.mention + ".")
                    else:
                        if heldGame.canBuzz(text.author):
                            if len(heldGame.buzzes) < 1:
                                heldGame.buzz(text.author)
                                print("Buzzed!")
                                report = text.author.mention + " buzzed. Pinging reader: " + str(
                                    heldGame.reader.mention)
                                await text.channel.send(report)
                            else:
                                heldGame.buzz(text.author)
                                report = "Held a buzz."
                                print("Buzzed!")
                                # because I don't want the bot to say anything if you buzz when someone has been recognized, each conditional needs its own await send.
                        else:
                            report = "Your team is locked out of buzzing, " + text.author.mention + "."
                            await text.channel.send(report)
                else:
                    report = "We are currently playing a bonus. You cannot buzz, " + text.author.mention + "."
                    await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

        if text.content.startswith('!github'):
            print("calling github")
            botSpoke = True
            emb = discord.Embed(title="Lev's Quizbowl Bot",
                                description="",
                                color=0x57068C)
            emb.add_field(
                name="View this bot's source code at:",
                value=
                "https://github.com/LevBernstein/LevQuizbowlBot/tree/pandasRewrite",
                inline=True)
            await text.channel.send(embed=emb)
            report = "Embedded github."
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if text.content.startswith('!report'):
            print("calling report")
            botSpoke = True
            emb = discord.Embed(title="Report bugs or suggest features",
                                description="",
                                color=0x57068C)
            emb.add_field(
                name="Report any issues at:",
                value="https://github.com/LevBernstein/LevQuizbowlBot/issues",
                inline=True)
            await text.channel.send(embed=emb)
            report = "Embedded report."
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if text.content.startswith('!help') or text.content.startswith(
                '!commands') or text.content.startswith('!tutorial'):
            print("calling tutorial")
            emb = discord.Embed(title="Lev's Quizbowl Bot Commands",
                                description="",
                                color=0x57068C)
            emb.add_field(
                name="!setup",
                value="Run this once, after the bot first joins the server.",
                inline=True)
            emb.add_field(name="!start",
                          value="Starts a new game.",
                          inline=True)
            emb.add_field(name="buzz", value="Buzzes in.", inline=True)
            emb.add_field(
                name="!clear",
                value="Clears buzzes without advancing the TU count.",
                inline=True)
            emb.add_field(
                name="!dead",
                value=
                "Clears buzzes after a dead TU and advances the TU count.",
                inline=True)
            emb.add_field(
                name="!score",
                value="Displays the score, sorted from highest to lowest.",
                inline=True)
            emb.add_field(
                name="Any whole number",
                value=
                "After a buzz or a bonus, the reader can enter a +/- whole number to assign points.",
                inline=True)
            emb.add_field(
                name="!call",
                value=
                "Mentions everyone in the server and informs them that it is time for practice. Usable only by admins.",
                inline=True)
            emb.add_field(name="!github",
                          value="Gives you a link to this bot's github page.",
                          inline=True)
            emb.add_field(
                name="!report",
                value="Gives you a link to this bot's issue-reporting page.",
                inline=True)
            emb.add_field(name="!tu",
                          value="Reports the current tossup number.",
                          inline=True)
            emb.add_field(
                name="!team [red/blue/green/orange/yellow/purple]",
                value=
                "Assigns you the team role corresponding to the color you entered.",
                inline=True)
            emb.add_field(
                name="!bonusmode",
                value=
                "Disables or enables bonuses. Bonuses are enabled by default.",
                inline=True)
            emb.add_field(name="!bstop",
                          value="Kills an active bonus without giving points.",
                          inline=True)
            emb.add_field(name="!newreader <@user>",
                          value="Changes a game's reader to another user.",
                          inline=True)
            emb.add_field(name="wd", value="Withdraws a buzz.", inline=True)
            # emb.add_field(name = "!undo", value = "Reverts the last score change.", inline = True) # DEPRECATED until I figure out the issue with TUnum tracking.
            emb.add_field(name="!end",
                          value="Ends the active game.",
                          inline=True)
            emb.add_field(name="!tutorial",
                          value="Shows you this list.",
                          inline=True)
            #emb.add_field(name = "_ _", value = "_ _", inline = True) # filler for formatting
            await text.channel.send(embed=emb)
            report = "Embedded commands list."
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if exist and text.content.startswith(
                '!tu'
        ):  # Placed after !help so that it won't fire when someone does !tutorial, a synonym of !help
            print("calling tu")
            report = "Current TU: #" + str(heldGame.TUnum + 1) + "."
            await text.channel.send(report)
            writeOut(generateLogs, text.author.name, text.content, heldGame,
                     report, botSpoke)
            return

        if text.content.startswith('!team'):
            """ Adds the user to a given team.
            Teams require the following roles: Team red, Team blue, Team green, Team orange, Team yellow, Team purple.
            If you do not have those roles in your server, the bot will create them for you when you run !setup. 
            Depending on your role hierarchy, the bot-created roles might not show their color for each user.
            Make sure that, for non-admin users, the team roles are the highest they can have in the hierarchy.
            Admin roles should still be higher than the team roles.
            """
            print("calling team")
            botSpoke = True
            rolesFound = False
            roles = ["red", "blue", "green", "orange", "yellow", "purple"]
            report = "Uh-oh! The Discord role you are trying to add does not exist! If whoever is going to read does !start, I will create the roles for you."
            for role in roles:
                if text.content.startswith('!team ' + role):
                    rolesFound = True
                    givenRole = get(text.guild.roles, name='Team ' + role)
                    if givenRole:
                        await text.author.add_roles(givenRole)
                        report = "Gave you the Team " + role + " role, " + text.author.mention + "."
                    break
            if not rolesFound:
                report = "Please choose a valid team! Valid teams are red, blue, green, orange, yellow, and purple."
            await text.channel.send(report)
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return
        's', 'onto', 'over', 'since', 'than', 'through', 'to', 'under',\
        'until', 'up', 'upon', 'the',  'with', 'without']
etc_pivots = create_shallow_pivot_dict(ETC)
pivots_list.append(etc_pivots)

# go through all episodes
for ep_num in range(1, NUM_EPS + 1):
    print('Processing episode: ' + str(ep_num) + '/' + \
        str(NUM_EPS))

    # get instance text for this episode
    instance_text_filename = INSTANCES_FOLDER + (EP_NUMBER_FORMAT % ep_num)
    instance_texts = []
    with open(instance_text_filename, 'r') as instance_text_file:
        instance_texts = instance_text_file.readlines()

    # clear vector file for this episode
    vector_filename = VECTORS_FOLDER + (EP_NUMBER_FORMAT % ep_num)
    with open(vector_filename, 'w') as vector_file:
        vector_file.close()

    instance_i = 0
    # go through all instance text lines
    for instance_text in instance_texts:
        print('\tProcessing instance: ' + str(instance_i + 1) + '/' + \
            str(len(instance_texts)))
        # write vector for this instance to file
        instance = Instance(instance_text, label_to_nums, pivots_list)
        instance.write_vector_to_file(vector_filename)
        instance_i += 1
示例#17
0
glossy = GlossyReflective(1, 1, 1, Sred, 50000, 1.0, Sred, r_sample)

#Objects

plane = Plane(Point(0, -15, 0), Vector(0, 1, -0.1), greymat)
world.addObject(plane)
plane2 = Plane(Point(0, 0, 20), Vector(0, 0, 1), bluemat)
world.addObject(plane2)

#Reflective Spheres
s3 = Sphere(Point(-22, 0, -3), 10.0, glossy)
world.addObject(s3)

#Instance
sphere = Sphere(Point(0, 0, -5), 5.0, mat)
s_i = Instance(sphere)
s_i.translate(25, 10, 0)
s_i.scale(1, 2, 1)
world.addObject(s_i)

#Transparent Sphere
c = Point(0, 0, -5)
r = 10.0
s = Sphere(c, r, transparent)
world.addObject(s)

#Texture Sphere
image = Image.open("earthmap1k.jpg")
texels = image.load()
sphere_map = SphericalMapping(8.0)
sampler = Regular(25, 83)