Beispiel #1
0
def plot_avg_training_traces(scores_dict):
    fig = plt.figure(figsize=(20, 30))
    for i, model in enumerate(list(scores_dict.keys())):
        tmp=scores_dict[model]
        if i<=3:
            # currently, only support for different linestyles for at most four models
            linestyle=LINESTYLES[i]
        else:
            linestyle='-'
        plt.subplot(211)
        plot_avg_scores_with_confidence(tmp['scores'], model_name=model,
                                        color=random_color(i), linestyle=linestyle)
        plt.subplot(212)
        plot_avg_scores_with_confidence(tmp['window-avg-scores'], model_name=model,
                                        color=random_color(i), linestyle=linestyle)

    plt.xlabel('#Episodes')
    plt.subplot(211)
    plt.ylabel('score')
    plt.axhline(y=GOAL_SCORE, color='y', linestyle='--', label="goal_score")
    plt.subplot(212)
    plt.ylabel('avg-100-score')
    plt.axhline(y=GOAL_SCORE, color='y', linestyle='--', label="goal_score")
    plt.ylim(top=GOAL_SCORE + 1.0)
    plt.legend()

    return fig
def set_vector_legend(legend, alpha_factor, symbol_layer=None):
    """
    Function to fill legend attributes with values from the symbolLayer
    """
    # Set default values for the case that layer_symbol arguments is not declared
    legend.set('BackColor', '')
    legend.set('LineColor', '')
    legend.set('Width', '2')
    legend.set('ImagePath', '')
    legend.set('ImageScale', '1')
    legend.set('EnableHatch', 'False')
    legend.set('Hatch', '0')
    legend.set('FieldName', '')
    legend.set('DashPattern', '')  # FIXME Need to understand how dash Pattern is read in gison3dmap
    legend.set('CampoRotacao', '')
    legend.set('CorSel', '255,255,255,0')

    # Check the type of symbolLayer and fill the legend attributes according
    if symbol_layer:
        layer_type = symbol_layer.layerType()
        properties = symbol_layer.properties()

        if layer_type == 'SimpleFill':
            if properties['style'] != 'no':
                legend.set('BackColor', utils.rgba2argb(properties['color'],alpha_factor))

            if properties['style'] not in ('solid','no'):
                legend.set('EnableHatch', 'True')
                legend.set('Hatch', '0') # FIXME:: Hatchs in QGIS are different from gison3dmap

            if properties['outline_style'] != 'no':
                legend.set('LineColor', utils.rgba2argb(properties['outline_color'],alpha_factor))

            legend.set('Width', utils.mm2px(properties['outline_width']))
            legend.set('DashPattern', '')  # ??

        elif layer_type == 'SimpleMarker':
            print properties
            legend.set('BackColor', utils.rgba2argb(properties['color'],alpha_factor))

            if properties['outline_style'] != 'no':
                legend.set('LineColor', utils.rgba2argb(properties['outline_color'],alpha_factor))

            legend.set('Width', utils.mm2px(properties['size']))
            legend.set('DashPattern', '')  # ??

        elif layer_type == 'SimpleLine':
            if properties['line_style'] != 'no':
                legend.set('LineColor', utils.rgba2argb(properties['line_color'],alpha_factor))
            legend.set('Width', utils.mm2px(properties['line_width']))
            legend.set('DashPattern', '')  # ??

        elif layer_type == 'ImageFill':
            legend.set('ImagePath', properties['imageFile'])
            legend.set('ImageScale', '1')
        else:
            legend.set('BackColor', utils.random_color())
            legend.set('LineColor', utils.random_color())
 async def execute_command(self, msg):
     args = msg.content.split()
     if len(args) < 2:
         await msg.channel.send(text='Please add a name for the event!',
                                delete_after=5)
         return
     events = await self.show_server_events(msg)
     if args[1] in ['stop', 'remove', 'end', 'cancel']:
         if len(args) < 3:
             await msg.channel.send(
                 text='Which event do you want to delete?', delete_after=5)
             return
         e = msg.content.replace('{} {} '.format(args[0], args[1]), '', 1)
         if e not in events.keys():
             await msg.channel.send(text='No such event.', delete_after=5)
         else:
             await self.remove_server_event(msg, e, events[e])
         return
     if args[1] in ['show', 'events', 'see'] and len(args) == 2:
         if events is None:
             await msg.channel.send(text='No scheduled events.',
                                    delete_after=5)
             return
         embed_var = EmbedWrapper(discord.Embed(title='Scheduled events',
                                                color=random_color()),
                                  embed_type='EVENT',
                                  marks=EmbedWrapper.INFO)
         for k, v in events.items():
             embed_var.add_field(name=k, value=v)
         await msg.channel.send(embed=embed_var, reactions=waste_basket)
         return
     name = msg.content.replace('{} '.format(args[0]), '', 1)
     if events is not None and name in events.keys():
         await msg.channel.send(
             text='Event with this name already exists in this server.',
             delete_after=5)
         return
     embed_var = EmbedWrapper(discord.Embed(
         title=name,
         description='date:\ntime:\nchannel: {}\ntext:\ntags:'.format(
             msg.channel.id),
         color=random_color()),
                              embed_type='EVENT',
                              marks=EmbedWrapper.INFO)
     embed_var.set_footer(
         text=('* Add options by replying "<opt> <value>" ' +
               '\n* Multiple options can be added at one,' +
               ' separated with ";".\n' +
               '* Date should be given in day and month format.\n' +
               '* Time should be given in hours and minutes format.\n'
               '* Name can also be changed.\n' +
               '* Channel should be given with its name.\n'
               '* After adding desired options (date and time are ' +
               'mandatory) reply "commit" to start the event.\n' +
               'Example:\n"date 27. 7.; time 16:00; text Test text; "' +
               'name new_name; tags test_tags; channel general; commit".'))
     await msg.channel.send(embed=embed_var)
    def on_add_clicked(self, button=None, start_date=None, due_date=None):
        """
        Adds a new task, with the help of a pop-up dialog
        for entering the task title, start and due dates.
        Redraw the calendar view after the changes.
        """
        # only to make testing easier
        if tests and not start_date and not due_date:
            today = datetime.date.today()
            start = random.choice(range(today.day, 31))
            end = random.choice(range(start, 31))
            start_date = str(today.year) + "-" + str(today.month) + "-" + str(start)
            due_date = str(today.year) + "-" + str(today.month) + "-" + str(end)
        ####
        dialog = TaskView(self.window, new=True)
        dialog.set_task_title("My New Task")
        if start_date:
            dialog.set_start_date(start_date)
        if due_date:
            dialog.set_due_date(due_date)

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            title = dialog.get_title()
            start_date = dialog.get_start_date()
            due_date = dialog.get_due_date()
            color = random_color()
            self.current_view.add_new_task(title, start_date, due_date, color)
            self.statusbar.push(0, "Added task: %s" % title)
        else:
            self.statusbar.pop(0)
        dialog.hide()
Beispiel #5
0
def generate_triangle(n):
    """
    Generates 'n' images of randomly generated triangles
    Saves it to a subdirectory within the DATA_DIR
    @param: n: int
    @return: None
    """

    # Padding for filenames
    padding = len(str(n))

    for i in range(n):

        # Generate random coordinates of the 3 vertices of the triangle
        while True:
            v1 = (randint(0, WIDTH - 1), randint(0, HEIGHT - 1))
            v2 = (randint(0, WIDTH - 1), randint(0, HEIGHT - 1))
            v3 = (randint(0, WIDTH - 1), randint(0, HEIGHT - 1))
            if verify_vertices(v1, v2, v3):
                break

        # Create a new Image
        image = Image.new("RGB", (WIDTH, HEIGHT), WHITE)
        draw = ImageDraw.Draw(image)

        # Draw the triangle with a random outline color
        draw.polygon([v1, v2, v3], outline=random_color())

        # Filepath of the image
        image_path = os.path.join(os.path.join(DATA_DIR, "Triangle"),
                                  f"{str(i).zfill(padding)}.png")
        # Save the image having 'i' as its filename formatted to n's number of digits
        image.save(image_path)
        print(f"Saved image to {image_path}...")
Beispiel #6
0
 def draw(self):
     if self.draw_line is None:
         with self.game.canvas:
             Color(*utils.random_color(), mode="rgba")
             self.draw_line = Line(points=self.draw_vertices, width=3)
     else:
         self.draw_line.points = self.draw_vertices
Beispiel #7
0
    async def _stare(self,
                     ctx,
                     members: commands.Greedy[discord.Member],
                     *,
                     reason: commands.clean_content = ''):
        if not members:
            return await ctx.send(
                ctx.t('commands.stare.noMention', {
                    "emoji": self.disco.emoji["false"],
                    "author": ctx.author.name
                }))

        if ctx.author in members:
            return await ctx.send(
                ctx.t('commands.stare.selfMention', {
                    "emoji": self.disco.emoji["false"],
                    "author": ctx.author.name
                }))

        image = await self.weeb.random_image('stare')
        emoji = random_choice(self.disco.emoji['stare'])
        phrase = random_choice(
            ctx.t('commands.stare.withReason'
                  if reason else 'commands.stare.noReason')).format(
                      author=ctx.author.name,
                      members=', '.join(f'**{m.name}**'
                                        for m in list(set(members))[:3]),
                      reason=reason[:1500],
                  )

        em = discord.Embed(colour=random_color()).set_image(
            url=image.url).set_footer(
                text=f'{ctx.author} | Powered by Weeb.sh')

        await ctx.send(content=f'{emoji} | {phrase}', embed=em)
Beispiel #8
0
 def setup(self):
     """Override this to run code at plugin startup, you can for
     example draw to the launchpad when this is called. This
     non-sense implementation just gives every pad that is in use a
     random color."""
     for pad in self.pads():
         self.launchpad.note_on(pad, random_color())
Beispiel #9
0
def generate_rectangle(n):
    """
    Generates 'n' images of randomly generated rectangles
    Saves it to a subdirectory within the DATA_DIR
    @param: n: int
    @return: None
    """

    # Padding for filenames
    padding = len(str(n))

    for i in range(n):
        # Generate 2 random sides that must not be equal to each other
        while True:
            s1, s2 = randint(5, WIDTH - 1), randint(5, HEIGHT - 1)
            # if both numbers are unique; break out of the loop
            if s1 != s2:
                break

        # Coordinates of top-left corner of the square
        x, y = randint(0, WIDTH - s1 - 1), randint(0, HEIGHT - s2 - 1)

        # Create a new Image
        image = Image.new("RGB", (WIDTH, HEIGHT), WHITE)
        draw = ImageDraw.Draw(image)

        # Draw the rectangle with a random outline color
        draw.rectangle([x, y, x + s1, y + s2], outline=random_color())

        # Filepath of the image
        image_path = os.path.join(os.path.join(DATA_DIR, "Rectangle"),
                                  f"{str(i).zfill(padding)}.png")
        # Save the image having 'i' as its filename formatted to n's number of digits
        image.save(image_path)
        print(f"Saved image to {image_path}...")
Beispiel #10
0
def generate_circle(n):
    """
    Generates 'n' images of randomly generated circles
    Saves it to a subdirectory within the DATA_DIR
    @param: n: int
    @return: None
    """

    # Padding for filenames
    padding = len(str(n))

    for i in range(n):

        # Generate a random radius
        r = randint(5, WIDTH - 1)
        # Coordinates of the top-left corner of the bounding box
        x, y = randint(0, WIDTH - r - 1), randint(0, HEIGHT - r - 1)

        # Create a new Image
        image = Image.new("RGB", (WIDTH, HEIGHT), WHITE)
        draw = ImageDraw.Draw(image)

        # Draw the circle with a random outline color
        draw.ellipse([x, y, x + r, y + r], outline=random_color())

        # Filepath of the image
        image_path = os.path.join(os.path.join(DATA_DIR, "Circle"),
                                  f"{str(i).zfill(padding)}.png")
        # Save the image having 'i' as its filename formatted to n's number of digits
        image.save(image_path)
        print(f"Saved image to {image_path}...")
Beispiel #11
0
 def setup(self):
     """Override this to run code at plugin startup, you can for
     example draw to the launchpad when this is called. This
     non-sense implementation just gives every pad that is in use a
     random color."""
     for pad in self.pads():
         self.launchpad.note_on(pad, random_color())
Beispiel #12
0
def set_break(legend, value_break, layer_alpha):
    """
    Create legend's breaks to represent categories or ranges

    :param value_break: range or category object
    """
    symbol = value_break.symbol()
    alpha_factor = symbol.alpha() * layer_alpha

    symbol_layer = symbol.symbolLayers()[0]
    layer_type = symbol_layer.layerType()
    properties = symbol_layer.properties()

    # Create a new break sub-element in legend
    legend_break = ET.SubElement(legend, 'Break')

    # setting default values
    color = ''
    line_color = ''
    if layer_type == 'SimpleMarker' or layer_type == 'SimpleFill':
        if properties['style'] != 'no':
            color = utils.rgba2argb(properties['color'],alpha_factor)
        if properties['outline_style'] != 'no':
            line_color = utils.rgba2argb(properties['outline_color'],alpha_factor)
        line_width = properties['outline_width']

    elif layer_type == 'SimpleLine':
        if properties['line_style'] != 'no':
            line_color = utils.rgba2argb(properties['line_color'],alpha_factor)
        line_width = properties['line_width']
    else:
        color = utils.random_color()
        line_color = '255,0,0,0'
        line_width = '1'
        print "Not possible to render the symbol properly a default was used instead"

    legend_break.set('EndColor', color)
    legend_break.set('StartColor', color)
    legend_break.set('OutlineEndColor', line_color)
    legend_break.set('OutlineStartColor', line_color)

    # Check if value_break has a single value or a lower and upper value
    # This is the only difference between graduated ranges and categorized categories
    try:
        # This will run for graduated layers
        legend_break.set('StartText', "{:.9f}".format(value_break.lowerValue()))
        legend_break.set('EndText', "{:.9f}".format(value_break.upperValue()))
    except AttributeError:
        # This will run for categorized layers
        value = value_break.value()
        # Convert to string in case of non string values
        if not isinstance(value, basestring):
            value = unicode(value)
        legend_break.set('StartText', value) # FIXME::Must check if values are always strings
        legend_break.set('EndText', value)

    legend_break.set('Rotulo', value_break.label())
    legend_break.set('Imagem', '')
    legend_break.set('Width', str(utils.mm2px(line_width)))
Beispiel #13
0
 def draw(self):
     if self.draw_line is None:
         with self.game.canvas:
             Color(*utils.random_color(), mode="rgba")
             self.draw_line = Line(points=self.draw_vertices,
                                   width=3)
     else:
         self.draw_line.points = self.draw_vertices
    def populate(self):
        # hard coded tasks to populate calendar view
        # (title, start_date, due_date, done?, color)
        today = datetime.date.today()
        ex_tasks = [("task1", today, today, True, random_color()),
                    ("task2", today + datetime.timedelta(days=5),
                    today + datetime.timedelta(days=5), False, random_color()),
                    ("task3", today + datetime.timedelta(days=1),
                    today + datetime.timedelta(days=3), False, random_color()),
                    ("task4", today + datetime.timedelta(days=3),
                    today + datetime.timedelta(days=4), True, random_color()),
                    ("task5", today - datetime.timedelta(days=1),
                    today + datetime.timedelta(days=8), False, random_color()),
                    ("task6: very long title",
                    today + datetime.timedelta(days=2),
                    today + datetime.timedelta(days=3), False, random_color()),
                    ("task7", today + datetime.timedelta(days=5),
                    today + datetime.timedelta(days=15), False, random_color())
                    ]

        for i in range(0, len(ex_tasks)):
            new_task = self.new_task()
            new_task.set_title(ex_tasks[i][0])
            new_task.set_start_date(ex_tasks[i][1])
            new_task.set_due_date(ex_tasks[i][2])
            if ex_tasks[i][3]:
                new_task.set_status(Task.STA_DONE)
            new_task.set_color(ex_tasks[i][4])
Beispiel #15
0
def visualize_contours(contours, image, winname):
    contours = sorted(contours, key=lambda c: c.len(), reverse=True)
    wnd = CvNamedWindow(winname, cv2.WINDOW_NORMAL)
    for part in contours:
        cv2.drawContours(image, [part.points()], -1, utils.random_color(), 2)
        print('part', part.len())
        wnd.imshow(image)
        cv2.waitKey()
    wnd.destroy(winname)
Beispiel #16
0
    def markersToDisplayImage(self, markers):
        disp = np.zeros([*markers.shape[:2], 3], np.uint8)
        for m in np.unique(markers):
            if m in (-1, 1):
                continue
            rr, cc = np.where(markers == m)
            disp[rr, cc] = utils.random_color()

        return disp
Beispiel #17
0
    def markersToDisplayImage(markers, objectsCount):
        displayImage = np.zeros([*markers.shape[:2], 3], np.uint8)

        for objectLabel in range(objectsCount):
            objectLabel = objectLabel + 2
            rr, cc = np.where(markers == objectLabel)
            displayImage[rr, cc] = utils.random_color()

        return displayImage
Beispiel #18
0
    def draw(self, x, y):
        x1, y1 = self.init_pos

        if self.draw_triangle is not None:
            mouse_x_y = x, y

            vertices = utils.constructTriangleFromLine(self.init_pos, mouse_x_y)
            self.draw_triangle.points = vertices
            self.draw_altitude.points = [x, y, x1, y1]
        else:
            with self.game.canvas:
                self.color = utils.random_color()
                Color(*self.color, mode="rgba")
                self.draw_triangle = Triangle(
                    points=utils.get_triangle_points(x1, y1, x, y))
                Color(*utils.random_color(), mode="rgba")
                self.draw_altitude = \
                    Line(points=[x1, y1, x, y],
                         width=LINE_WIDTH, cap="square")
Beispiel #19
0
 def loop(self):
     if self.shared.loop_i % 10 == 0:
         if self.seedrandom['text'] == "Random":
             self.seedrandom.config(activeforeground=random_color())
         else:
             self.seedrandom.config(activeforeground='#faaffa')
     if getattr(self.shared, "prof_upd_required", False):
         self.update_profiler()
         self.shared.prof_upd_required = False
     self.after(50, self.loop)
     self.shared.loop_i += 1
Beispiel #20
0
 def draw(self, x, y):
     if self.draw_line is not None:
         self.draw_line.points = [self.init_pos[0], self.init_pos[1], x, y]
     elif self.init_pos:
         with self.game.canvas.after:
             self.color = utils.random_color()
             # print "drawing tool:", self.color
             Color(*self.color, mode="rgba")
             self.draw_line = \
                 Line(points=[self.init_pos[0], self.init_pos[1], x, y],
                      width=LINE_WIDTH)
Beispiel #21
0
    def draw(self, x, y):
        x1, y1 = self.init_pos

        if self.draw_triangle is not None:
            mouse_x_y = x, y

            vertices = utils.constructTriangleFromLine(self.init_pos,
                                                       mouse_x_y)
            self.draw_triangle.points = vertices
            self.draw_altitude.points = [x, y, x1, y1]
        else:
            with self.game.canvas:
                self.color = utils.random_color()
                Color(*self.color, mode="rgba")
                self.draw_triangle = Triangle(
                    points=utils.get_triangle_points(x1, y1, x, y))
                Color(*utils.random_color(), mode="rgba")
                self.draw_altitude = \
                    Line(points=[x1, y1, x, y],
                         width=LINE_WIDTH, cap="square")
Beispiel #22
0
 def draw(self, x, y):
     if self.draw_line is not None:
         self.draw_line.points = [self.init_pos[0], self.init_pos[1], x, y]
     elif self.init_pos:
         with self.game.canvas.after:
             self.color = utils.random_color()
             # print "drawing tool:", self.color
             Color(*self.color, mode="rgba")
             self.draw_line = \
                 Line(points=[self.init_pos[0], self.init_pos[1], x, y],
                      width=LINE_WIDTH)
Beispiel #23
0
def walk_cv_contours_by_kbd(polylines, base_img):
    for poly in polylines:
        img = base_img.copy()
        cv2.polylines(img, [poly], False, utils.random_color(), thickness=2)
        utils.imshow(dd=img)
        if cv2.waitKey() == 27:
            return

    if len(polylines):
        while cv2.waitKey() != 27:
            pass
Beispiel #24
0
 async def starting_embed(self, title, msg):
     embed_var = EmbedWrapper(discord.Embed(
         color=random_color(),
         description='* {}\n* {}\n{}'.format(
             'Reply with a role to add it to the message.',
             'You can add multiple at once, separated with ";".',
             'Example: "role1;role2;role3"')),
                              embed_type='ROLES',
                              marks=EmbedWrapper.NOT_DELETABLE)
     if title is not None:
         embed_var.title = title
     return embed_var
def parse_config_args(config: dict) -> list:
    args = []
    for key, value in config['args'].items():
        if key == '--reproduce-chance':
            args.append(key)
            if value['start'] is not None:
                args.append(str(uniform(value['start'], value['end'])))
            elif value['value']:
                args.append(str(value['value']))
            else:
                args.append(str(uniform(0.5, 1)))
        elif 'percent' in key:
            if value['start'] is not None:
                args.append(key)
                args.append(str(uniform(value['start'], value['end'])))
            elif value['value']:
                args.append(key)
                args.append(str(value['value']))
        elif key == '--starting-point':
            if value['random']:
                args.append(key)
                args.append(str(randint(1, int(config['width']))))
                args.append(str(randint(1, int(config['height']))))
            elif value['valueX']:
                args.append(key)
                args.append(str(value['valueX']))
                args.append(str(value['valueY']))
        elif key == '--color-background':
            if value['random']:
                args.append(key)
                # cc - color component
                for cc in random_color():
                    args.append(str(cc))
            elif value['value']:
                args.append(key)
                # cc - color component
                for cc in value['value']:
                    args.append(str(cc))
        elif key == '--max-count' or key == '--colors-number':
            if value['start'] is not None:
                args.append(key)
                args.append(str(randint(value['start'], value['end'])))
            elif value['value']:
                args.append(key)
                args.append(str(value['value']))
        elif type(value) is dict:
            if value['random']:
                if bool(getrandbits(1)):
                    args.append(key)
            elif value['value']:
                args.append(key)
    args.append('--dont-show-image')
    return args
 async def send_event(self, channel_id, event, text, tags):
     # send scheduled event at the right time
     # timed by threading.Timer()
     channel = self.bot.client.get_channel(int(channel_id))
     if channel is None:
         return
     embed_var = EmbedWrapper(discord.Embed(title=event,
                                            color=random_color(),
                                            description=text),
                              embed_type="EVENT",
                              marks=EmbedWrapper.INFO)
     await channel.send(text=None if len(tags) < 1 else tags,
                        embed=embed_var)
Beispiel #27
0
def plot_best_training_traces(scores_dict):
    fig = plt.figure(figsize=(20,30))
    for i, model in enumerate(list(scores_dict.keys())):
        j = np.argmin([len(scores) for scores in scores_dict[model]['scores']]) # find the most efficient (least time spent) trial
        scores=scores_dict[model]['scores'][j]
        avg_scores=scores_dict[model]['window-avg-scores'][j]
        x=np.arange(len(scores))
        plt.subplot(211)
        plt.plot(x, scores, label=model, color=random_color(i))
        plt.subplot(212)
        plt.plot(x, avg_scores, label=model, color=random_color(i))

    plt.xlabel('#Episodes')
    plt.subplot(211)
    plt.ylabel('score')
    plt.axhline(y=GOAL_SCORE, color='y', linestyle='--', label="goal_score")
    plt.subplot(212)
    plt.ylabel('avg-100-score')
    plt.axhline(y=GOAL_SCORE, color='y', linestyle='--', label="goal_score")
    plt.ylim(top=GOAL_SCORE + 1.0)
    plt.legend()
    return fig
Beispiel #28
0
def plot_avg_scores_with_confidence(scores, model_name, color=random_color(), linestyle='-'):
    l = min_len_list_of_lists(scores)
    scores = [score[:l] for score in scores]

    mean_score = np.mean(scores, axis=0)
    std_score = np.std(scores, axis=0)

    x = np.arange(l)
    n_exps = len(scores)
    plt.plot(x, mean_score, color=color, label=model_name, linestyle=linestyle)
    plt.fill_between(x, mean_score - 2*std_score / np.sqrt(n_exps),
                        mean_score + 2*std_score / np.sqrt(n_exps),
                        alpha=0.2, color=color)
Beispiel #29
0
    async def _cry(self, ctx, *, reason: commands.clean_content = ''):
        image = await self.weeb.random_image('cry')
        emoji = random_choice(self.disco.emoji['cry'])
        phrase = random_choice(
            ctx.t('commands.cry.withReason' if reason else
                  'commands.cry.noReason')).format(author=ctx.author.name,
                                                   reason=reason[:1500])

        em = discord.Embed(colour=random_color()).set_image(
            url=image.url).set_footer(
                text=f'{ctx.author} | Powered by Weeb.sh')

        await ctx.send(content=f'{emoji} | {phrase}', embed=em)
Beispiel #30
0
 def starting_embed(self, question):
     poll_embed = EmbedWrapper(discord.Embed(
         title='Q:\u2000' + question,
         color=random_color(),
         description='* {}\n* {}\n* {}\n* {}\n* {}\n{}'.format(
             'Reply to this message to add a response.',
             'Reply "remove <idx>" to remove response with index <idx>.',
             'Reply "fix" to disable adding or removing responses.',
             'Reply "end" to finish the poll.',
             'Multiple options can be added at once, separated with ";".\n',
             'Example: "response1; response2; remove 0; response3;fix"')),
                               embed_type='POLL',
                               marks=EmbedWrapper.NOT_DELETABLE)
     return poll_embed
Beispiel #31
0
 async def _send_image(self,
                       ctx,
                       url_image,
                       kind: str = None,
                       user: discord.Member = None):
     """A helper function that creates an embed with an image and sends it off."""
     if isinstance(url_image, (tuple, list)):
         url_image = systemrandom.choice(url_image)
     message = self._generate_message(ctx, kind, user)
     if not helpers.has_scanning(ctx):
         embed = discord.Embed(color=utils.random_color())
         embed.set_image(url=url_image)
         await ctx.send(message, embed=embed)
     else:
         message = "\n".join([str(message), url_image])
         await ctx.send(message)
Beispiel #32
0
 async def execute_command(self, msg):
     embed_var = utils.EmbedWrapper(discord.Embed(
         description="React with a game's emoji to start it.",
         color=utils.random_color()),
         embed_type='GAMES',
         marks=utils.EmbedWrapper.INFO)
     e_count = 0
     for k, v in self.bot.commands.items():
         if v.game:
             embed_var.add_field(name=v.embed_type,
                                 value=(utils.emojis[e_count] +
                                        ' ({})'.format(k)))
             e_count += 1
     await msg.channel.send(
         embed=embed_var, reactions=[
             utils.emojis[i] for i in range(e_count)])
Beispiel #33
0
def main():
    pm = PixelMatrix(pin, rows, cols)
    pm.clear()
    elapsed = 0

    while True:
        row = randrange(rows)
        col = randrange(cols)
        pm[(row, col)] = random_color(brightness=brightness)
        pm.write()
        time.sleep(wait_time)
        elapsed += wait_time

        if elapsed >= reset_time:
            elapsed = 0
            pm.clear()
Beispiel #34
0
 async def on_dm_reaction(self, payload):
     # check if rps dm message, then get channel id from
     # which the rps game was started
     # then send new embed to that channel and wait for another
     # opponent to join
     if (payload.emoji.name not in rps_emojis
             or payload.event_type != 'REACTION_ADD'):
         return
     user = self.bot.client.get_user(int(payload.user_id))
     if user is None:
         return
     reaction_msg = await user.fetch_message(payload.message_id)
     if reaction_msg is None or not reaction_msg.is_rps:
         return
     # edit chosen emoji to embed's title
     embed = reaction_msg.embeds[0]
     embed.title = payload.emoji.name
     embed.mark(embed.ENDED)
     await reaction_msg.edit(text=reaction_msg.content, embed=embed)
     # get channel id, message id from embed's footer
     info = embed.footer.text
     channel = None
     try:
         channel = self.bot.client.get_channel(int(info))
         if channel is None:
             raise ValueError
         user = channel.guild.get_member(payload.user_id)
         if user is None:
             raise ValueError
     except ValueError:
         return
     # create game embed and send it to channel where game was started
     new_embed = EmbedWrapper(discord.Embed(
         title='{} is waiting for an opponent'.format(
             user.name if not user.nick else user.nick),
         color=random_color()),
                              embed_type=self.embed_type,
                              marks=EmbedWrapper.NOT_DELETABLE)
     # if user has nickname set up use nickname, else use username
     new_embed.description = 'React with {}, {} or {} to join!'.format(
         rps_emojis[0], rps_emojis[1], rps_emojis[2])
     new_embed.set_footer(
         text='{}{}'.format(payload.message_id, user.id),
         icon_url=None if not user.avatar_url else user.avatar_url)
     # add users profile picture to the embed
     await channel.send(embed=new_embed, reactions=rps_emojis)
Beispiel #35
0
 async def execute_command(self, msg, user=None):
     # show leaderboard
     if user is None:
         args = msg.content.split()
         if len(args) > 1 and (args[1] == 'leaderboard' or args[1] == 'lb'):
             await self.show_leaderboard(msg)
             return
         user = msg.author
     # send dm to the user who started the game and
     # wait for him to react with one of the options
     dm = await user.create_dm()
     dm_embed = EmbedWrapper(discord.Embed(
         description='React with your weapon of choice!',
         color=random_color()),
                             embed_type=self.embed_type,
                             marks=EmbedWrapper.NOT_DELETABLE)
     dm_embed.set_footer(text=msg.channel.id)
     await dm.send(embed=dm_embed, reactions=rps_emojis)
Beispiel #36
0
    def __init__(self, x, y, behavior, window):
        """
            idealized vehicle representing a drone

            :param x and y: represents inicial target 
            :param behavior: State Machine 
            :param window: pygame screen were it will be draw
        """

        self.debug = False  #  debug lines is Off

        # Variables used to move drone
        self.location = vec2(random.uniform(0, SCREEN_WIDTH),
                             random.uniform(
                                 0,
                                 SCREEN_HEIGHT))  # Random position in screen
        self.velocity = vec2(0.1, 0)  # Inicial speed
        self.target = vec2(x, y)
        self.acceleration = vec2(0, 0)
        self.radius = SIZE_DRONE  # Drone Size
        self.desired = vec2()

        self.memory_location = []  # To draw track
        self.rotation = atan2(self.location.y,
                              self.location.x)  # inicital rotation

        # Arbitrary values
        self.max_speed = FORWARD_SPEED
        self.max_force = SEEK_FORCE
        self.angular_speed = ANGULAR_SPEED

        # Picks a random color for target, is used to differentiate visually during simulation
        self.color_target = random_color()

        # Variables related to State Machine
        self.behavior = behavior
        self.window = window  # tela em que esta acontecendo a simulaçao
        self.theta = 0  # variavel para o eight somada no seek_around
        self.count = 0

        # Variables to draw drone using Sprites
        self.drone = Aircraft()
        self.all_sprites = pg.sprite.Group()
        self.all_sprites.add(self.drone)
Beispiel #37
0
 async def execute_command(self, msg, user=None):
     # send a message and await second user to join with thumbs up reaction
     # if first word is lb or leaderboard show players with most wins
     if user is None:
         args = msg.content.split()
         if len(args) > 1 and args[1] in ['lb', 'leaderboard']:
             await self.show_leaderboard(msg)
             return
         user = msg.author
     name = user.name if not user.nick else user.nick
     embed_var = utils.EmbedWrapper(discord.Embed(
         description=('{} has challanged for a game of connect four.\n' +
                      'React with a token to join!\n').format(
                          name, utils.thumbs_up),
         color=utils.random_color()),
                                    embed_type=self.embed_type,
                                    marks=utils.EmbedWrapper.NOT_DELETABLE)
     embed_var.set_footer(text=user.id)
     await msg.channel.send(embed=embed_var, reactions=self.tokens)
Beispiel #38
0
def api_update_link():
    req = request.get_json()
    print req
    url = req['url']

    title = req['title']
    tags = list(set(req['tags'].replace(',', ' ').split(' ')))
    tags = [tag.strip() for tag in tags if tag.strip()]
    description = req['description']
    favicon = ''
    if 'favicon' in req:
        favicon = req['favicon']

    user = models.User.objects(id=current_user.id).first()
    if user is None:
        return jsonify(succeed=False,
                       reason='User not exist')

    link = models.LinkPost.objects(user=user, url=url).first()
    if link is None:
        return jsonify(succeed=False,
                       reason='URL not exist'
                       )
    tags_data = []
    for tag in tags:
        try:
            cur_tag = models.Tag.objects(user=user, name=tag).first()
            if cur_tag is None:
                cur_tag = models.Tag()
                cur_tag.name = tag
                cur_tag.user = user
                cur_tag.color = utils.random_color()
                cur_tag.is_topic = tag.startswith('#')
                cur_tag.save()

            tags_data.append(cur_tag)
        except Exception, e:
            print 'update tag error :', e.message
            return jsonify(succeed=False,
                           reason='Update tags failed'
                           )
Beispiel #39
0
 async def show_leaderboard(self, msg):
     # show guild members that played fil in order
     # best to worst
     if self.bot.database.connected is False:
         await msg.channel.send(text='No database connection.',
                                delete_after=5)
         return
     cursor = self.bot.database.cnx.cursor(buffered=True)
     cursor.execute(
         "SELECT * FROM four_in_line WHERE guild_id = '{}'".format(
             msg.guild.id))
     fetched = cursor.fetchall()
     if fetched is []:
         await msg.channel.send(text='No availible leaderboard.',
                                delete_after=5)
         return
     embed_var = utils.EmbedWrapper(discord.Embed(
         title='Leaderboard', color=utils.random_color()),
                                    embed_type=self.embed_type,
                                    marks=utils.EmbedWrapper.INFO)
     users = {}
     for i in fetched:
         user = msg.guild.get_member(int(i[1]))
         if user is None:
             continue
         users[user] = i[2]
     users = {
         k: v
         for k, v in sorted(
             users.items(), key=lambda item: item[1], reverse=True)
     }
     i = 1
     for u, w in users.items():
         if i > 10:
             break
         name = u.name if not u.nick else u.nick
         embed_var.add_field(name='{}.  {}'.format(i, name),
                             value=w,
                             inline=False)
         i += 1
     await msg.channel.send(embed=embed_var, reactions=utils.waste_basket)
Beispiel #40
0
    def draw(self, x, y):
        d = int(utils.distance((x, y), self.init_pos))
        x1, y1 = self.init_pos

        if self.draw_circle is not None:

            self.draw_circle.pos = (x1-d, y1-d)
            self.draw_circle.size = (2*d, 2*d)

            self.draw_line.points = [x1, y1, x, y]
        else:
            with self.game.canvas:
                self.color = utils.random_color()
                Color(*self.color, mode="rgba")
                self.draw_circle = \
                    Ellipse(pos=(x+d, y+d),
                            size=(d/2, d/2))
                
                Color(*get_color_from_hex("#33B5E5"))
                self.draw_line = \
                    Line(points=[x1, y1, x, y],
                         width=LINE_WIDTH, cap="round")
Beispiel #41
0
    def draw(self, x, y):
        d = int(utils.distance((x, y), self.init_pos))
        x1, y1 = self.init_pos

        if self.draw_rectangle is not None:
            hw = abs(x1-x)
            hh = abs(y1-y)
            self.draw_rectangle.pos = (x1-hw, y1-hh)
            self.draw_rectangle.size = (2*hw, 2*hh)

            self.draw_line.points = [x1, y1, x, y]
        else:
            with self.game.canvas:
                self.color = utils.random_color()
                Color(*self.color, mode="rgba")

                self.draw_rectangle = \
                    Rectangle(pos=(x-d, y-d),
                              size=(d/2, d/2))
                
                Color(*get_color_from_hex("#33B5E5"), mode="rgba")
                self.draw_line = \
                    Line(points=[x1, y1, x, y],
                         width=LINE_WIDTH, cap="round")
Beispiel #42
0
def api_add_link():
    req = request.get_json()
    print req
    title = req['title']
    url = req['url']
    favicon = ''
    if 'favicon' in req:
        favicon = req['favicon']

    user = models.User.objects(id=current_user.id).first()
    if user is None:
        print 'user not exist : ' + str(current_user.id)
        return jsonify(succeed=False,
                       reason='User not exist')

    search_links = models.LinkPost.objects(user=user, url=url)
    if len(search_links) > 0:
        print 'url exist'
        return jsonify(succeed=False,
                       reason='URL exist'
                       )

    link = models.LinkPost()
    link.title = title
    link.user = user
    link.tags = []
    link.url = url
    link.color = utils.random_color()
    link.favicon = favicon

    try:
        link.save()
    except Exception, err:
        print 'link save error : '+ err.message
        return jsonify(succeed=False,
                       reason='Link save failed')
Beispiel #43
0
# Foundation; either version 2 of the License, or (at your option) any later
# version.
# 
# PyOmino 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 General Public License for more
# details.
# 
# You should have received a copy of the GNU General Public License along with
# PyOmino; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301, USA.

import base_piece, utils

DEFAULT_COLORS = {
    'tri_I': utils.random_color(),
    'tri_V': utils.random_color(),
    'tetr_T': (200, 200,  10),
    'tetr_I': ( 10, 200, 200),
    'tetr_O': (200,  10, 200),
    'tetr_L': (200,  10,  10),
    'tetr_J': ( 10, 200,  10),
    'tetr_S': ( 10,  10, 200),
    'tetr_Z': (150, 150, 150),
    'pent_W': utils.random_color(),
    'pent_Z': utils.random_color(),
    'pent_S': utils.random_color(),
    'pent_L': utils.random_color(),
    'pent_J': utils.random_color(),
    'pent_I': utils.random_color(),
    'pent_T': utils.random_color(),