Esempio n. 1
0
def train(epoch):
    running_loss = 0.0
    net.train()
    correct = 0
    total = 0
    progress_bar_obj = get_progress_bar(len(train_dataset_loader))
    print('Epoch', epoch, 'Train')
    for i, (inputs, labels) in enumerate(train_dataset_loader):
        inputs, labels = inputs.to(device), labels.to(
            device)  # this line doesn't work when use cpu
        # zero the parameter gradients
        optimizer.zero_grad()

        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        _, predicted = outputs.max(1)
        total += labels.size(0)
        correct += predicted.eq(labels).sum().item()
        update_progress_bar(progress_bar_obj,
                            index=i,
                            loss=(running_loss / (i + 1)),
                            acc=100. * (correct / total),
                            c=correct,
                            t=total)
Esempio n. 2
0
 def render_tab(self, ctx):
     # Update system info
     self.update_sysinfo()
     
     # Print CPU usage
     for i in range(0, len(self.cpu_usages)):
         cpu_usage = self.cpu_usages[i]
         
         ctx.fg_color(Screen.WHITE)
         
         ctx.write("CPU %d:" % i).fg_color(Screen.YELLOW).write_line(" %.2f %%" % (cpu_usage*100)).fg_color(Screen.WHITE).write("[")
         
         if cpu_usage < self.YELLOW_THRESHOLD:
             ctx.fg_color(Screen.GREEN)
         elif cpu_usage >= self.YELLOW_THRESHOLD and cpu_usage <= self.RED_THRESHOLD:
             ctx.fg_color(Screen.YELLOW)
         else:
             ctx.fg_color(Screen.RED)
             
         ctx.write(get_progress_bar(ctx.get_columns()-2, cpu_usage)).fg_color(Screen.WHITE).write("]")
         
     # Print RAM
     used = humanfriendly.format_size(self.used_ram)
     total = humanfriendly.format_size(self.total_ram)
     ctx.linebreak().write_line("RAM").fg_color(Screen.YELLOW).write_line("%s / %s" % (used, total)).fg_color(Screen.WHITE)
     
     ram_usage = float(self.used_ram) / float(self.total_ram)
         
     ctx.write("[")
     
     if ram_usage < 0.33:
         ctx.fg_color(Screen.GREEN)
     elif ram_usage >= 0.33 and ram_usage <= 0.66:
         ctx.fg_color(Screen.YELLOW)
     else:
         ctx.fg_color(Screen.RED)
         
     ctx.write(get_progress_bar(ctx.get_columns()-2, ram_usage)).fg_color(Screen.WHITE).write("]")
     
     # Print uptime
     ctx.linebreak().write_line("Uptime:").fg_color(Screen.YELLOW).write_line("%s" % format_timespan(self.uptime)).fg_color(Screen.WHITE)
Esempio n. 3
0
        async def execute(client, module, message, *args):
            # Show off user's level / xp 
            if message.channel.id != 358032526763360277:
                return

            user = message.author
            xp = module.users.get_user_xp(user.id)
            level = module.users.get_user_level(user.id)
            levelxp = '{}\n**Level {}**   {} / {} XP\n{}'.format(
                user.mention,
                level,
                xp,
                module.xp_needed_for_level(level),
                get_progress_bar(xp, module.xp_needed_for_level(level))
            )
            embed = discord.Embed(description=levelxp, color=discord.Color.purple())
            return embed
Esempio n. 4
0
 def render_tab(self, ctx):
     self.update_disk_usage()
     
     for device_name, usage in self.disk_usage.iteritems():
         ctx.write_line("%s" % device_name)
         
         ctx.fg_color(Screen.YELLOW).write_line("%s / %s" % (humanfriendly.format_size(usage["used"]),
                                                             humanfriendly.format_size(usage["total"])))
         
         ctx.fg_color(Screen.WHITE).write("[")
         
         usage_percent = float(usage["used"]) / float(usage["total"])
         
         if usage_percent < self.YELLOW_THRESHOLD:
             ctx.fg_color(Screen.GREEN)
         elif usage_percent >= self.YELLOW_THRESHOLD and usage_percent <= self.RED_THRESHOLD:
             ctx.fg_color(Screen.YELLOW)
         else:
             ctx.fg_color(Screen.RED)
             
         ctx.write(get_progress_bar(ctx.get_columns()-2, usage_percent)).fg_color(Screen.WHITE).write("]").linebreak()
Esempio n. 5
0
def train(epoch):
    running_loss = 0.0
    net.train()  # 这条代码似乎也不需要...
    correct = 0
    total = 0
    progress_bar_obj = get_progress_bar(len(trainloader))
    print('Epoch', epoch, 'Train')
    for i, data in enumerate(trainloader, 0):
        # get the inputs; data is a list of [inputs, labels]
        inputs, labels = data

        inputs, labels = inputs.to(device), labels.to(
            device)  # 在使用cpu的时候这条行代码自动忽略

        # 清零梯度缓存 zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # 打印统计数据 print statistics  在 batch_size 不为 4 的情况下打印不出计数,改用 kuangliu 的 progress_bar
        # running_loss += loss.item()
        # if i % 2000 == 1999:
        #     print('[%d, %5d] loss: %.3f' %
        #           (epoch + 1, i + 1, running_loss / 2000))
        #     running_loss = 0.0

        running_loss += loss.item()
        _, predicted = outputs.max(1)
        total += labels.size(0)
        correct += predicted.eq(labels).sum().item()
        update_progress_bar(progress_bar_obj,
                            index=i,
                            loss=(running_loss / (i + 1)),
                            acc=100. * (correct / total),
                            c=correct,
                            t=total)
Esempio n. 6
0
    async def on_member_join(self, member):
        punishment_fields = []
        notes = []
        moderation = self.client.request_module('moderation')
        if moderation:
            for punishment in moderation.punishments.select(where=['user=?', member.id]):
                punishment_fields.append({
                    'name': punishment['type'] + (' ({})'.format(punishment['end_length']) if punishment['end_length'] else ''),
                    'value': '{}\n**Mod:** <@{}> | **Date:** {} | **ID:** {}'.format(
                        ('`' + punishment['reason'] + '`').replace('`' + NO_REASON + '`', '*No reason was ever specified.*'),
                        punishment['mod'],
                        str(datetime.fromtimestamp(punishment['created']).date()),
                        punishment['id']
                    ),
                    'inline': False
                })

            for note in moderation.notes.select(where=['user=?', member.id]):
                notes.append('{tilde}{}{tilde}\n**Mod:** <@{}> | **Date:** {} | **ID:** {}'.format(
                    note['content'],
                    note['mod'],
                    str(datetime.fromtimestamp(note['created']).date()),
                    note['id'],
                    tilde='`'
                ))
        if len(punishment_fields) > 18:
            punishment_fields = punishment_fields[:17]

        xp = self.users.get_user_xp(member.id)
        level = self.users.get_user_level(member.id)
        # Show off user's level / xp 
        levelxp = '**Level {}**   {} / {} XP\n{}'.format(
            level,
            xp,
            self.xp_needed_for_level(level),
            get_progress_bar(xp, self.xp_needed_for_level(level))
        )
        if level >= 4:
            await member.add_roles(self.regular_role, reason='User rejoined and had regular role')

        if self.invites:
            ni = await self.client.focused_guild.invites()
            new_invites = {i.code: i.uses for i in ni}
            old_invites = {i.code: i.uses for i in self.invites}
            code_used = 'toontown'
            for code, uses in new_invites.items():
                # In the event that a new invite code was generated, but has not been used,
                # we'll skip it hackily by calling `old_invites.get(code, uses)` to bypass the second check.
                if (code not in old_invites and uses > 0) or old_invites.get(code, uses) != uses:
                    code_used = code
                    break
            self.invites = ni
        else:
            code_used = None

        await self.client.send_message(
            self.log_channel,
            self.create_discord_embed(
                action='Join',
                primary_info=str(member),
                secondary_info=member.mention,
                thumbnail=member.avatar_url,
                fields=[
                    {'name': 'Account Creation Date', 'value': str(member.created_at.date()), 'inline': True},
                    {'name': 'Join Date', 'value': str(member.joined_at.date()), 'inline': True},
                    {'name': 'Level / XP', 'value': levelxp, 'inline': True}
                ] + ([{'name': 'Notes', 'value': '\n\n'.join(notes), 'inline': False}] if notes else []) + punishment_fields,
                footer={'text': "Joined using invite code: {}".format(code_used)} if code_used else None
            )
        )
        self.member_status_time_start[member.id] = time.time()
Esempio n. 7
0
        async def execute(client, module, message, *args):
            # Get user the mod wants to lookup.
            if not args:
                user = message.author
            elif not message.mentions:
                if not message.raw_mentions:
                    try:
                        user = client.focused_guild.get_member(int(args[0])) or await client.fetch_user(int(args[0]))
                    except discord.NotFound:
                        moderation = client.request_module('moderation')
                        if moderation:
                            punishment_id = int(args[0])
                            punishment = moderation.punishments.select(where=["id=?", punishment_id], limit=1)
                            if not punishment:
                                return 'No known user / lookup ID'
                            try:
                                user = await client.fetch_user(punishment['user'])
                            except discord.NotFound:
                                return 'No known user / lookup ID'
                    except (ValueError, IndexError):
                        name = ' '.join(args)
                        discriminator = args[-1].split('#')[-1]
                        if discriminator:
                            name = ' '.join(args).rstrip('#0123456789')
                            user = discord.utils.get(message.guild.members, name=name, discriminator=discriminator)
                        user = discord.utils.get(message.guild.members, display_name=name) if not user else user
                        user = discord.utils.get(message.guild.members, name=name) if not user else user
                        if not user:
                            return 'No known user'
                else:
                    try:
                        user = client.focused_guild.get_member(message.raw_mentions[0]) or await client.fetch_user(message.raw_mentions[0])
                    except discord.NotFound:
                        return 'No known user'
            else:
                user = message.mentions[0]

            # Get all punishments for user, each will be an individual field in the embed.
            punishment_fields = []
            notes = []

            if assert_class(message.channel, discord.DMChannel, otherwise=False) or (message.channel.category and message.channel.category.name == 'Staff'):
                moderation = client.request_module('moderation')
                for punishment in moderation.punishments.select(where=['user=?', user.id]):
                    punishment_fields.append({
                        'name': punishment['type'] + (' ({})'.format(punishment['end_length']) if punishment['end_length'] else ''),
                        'value': '{}\n**Mod:** <@{}> | **Date:** {} | **ID:** {}'.format(
                            ('`' + punishment['reason'] + '`').replace('`' + NO_REASON + '`', '*No reason was ever specified.*'),
                            punishment['mod'],
                            str(datetime.fromtimestamp(punishment['created']).date()),
                            punishment['id']
                        ),
                        'inline': False
                    })

                for note in moderation.notes.select(where=['user=?', user.id]):
                    notes.append('{tilde}{}{tilde}\n**Mod:** <@{}> | **Date:** {} | **ID:** {}'.format(
                        note['content'],
                        note['mod'],
                        str(datetime.fromtimestamp(note['created']).date()),
                        note['id'],
                        tilde='`'
                    ))

            if len(punishment_fields) > 18:
                punishment_fields = punishment_fields[:17]
                """noteFields = noteFields[:18 - len(punishment_fields)]
                noteFields.append({
                    'name': 'MORE PUNISHMENTS / NOTES EXIST!', 
                    'value': 'All of the punishments / notes on this account cannot be displayed in an embed. Please delete some that are older or unneeded.',
                    'inline': False
                })"""

            # Get all channel participation
            messages = []
            channel_participation = module.users.get_user_message_overview(user.id)
            # A classic Computer Science solution eh? Too lazy for something clever
            most_channel_participation = [(None, -1, 0, 0, 0) for _ in range(3)]
            for channel, participation in channel_participation.items():
                channel = client.focused_guild.get_channel(int(channel))
                if not channel:
                    continue

                total_messages = participation['messages'] + participation['attachments'] + participation['embeds']
                for i in range(2, -1, -1):
                    if total_messages > most_channel_participation[i][1]:
                        if i != 0 and total_messages > most_channel_participation[i - 1][1]:
                            continue
                        else:
                            for j in range(1, i - 1, -1):
                                most_channel_participation[j + 1] = most_channel_participation[j]
                            most_channel_participation[i] = (channel, total_messages, participation['messages'], participation['attachments'], participation['embeds'])
            for channel, _, _messages, attachments, embeds in most_channel_participation:
                if channel:
                    messages.append('{} -> :envelope: **{}** | :paperclip: **{}** | :page_facing_up: **{}**'.format(
                        channel.mention,
                        _messages,
                        attachments,
                        embeds
                    ))
            if not messages:
                messages = ['¯\_(ツ)_/¯']

            # Get Discord statuses for the past however long we've been recording them...
            statuses = '**Online:** {}\n**Idle:** {}\n**Do Not Disturb:** {}\n**Offline / Invisible:** {}'.format(
                get_time_from_seconds(module.users.get_user_time_online(user.id), one_unit_limit=True),
                get_time_from_seconds(module.users.get_user_time_idle(user.id), one_unit_limit=True),
                get_time_from_seconds(module.users.get_user_time_dnd(user.id), one_unit_limit=True),
                get_time_from_seconds(module.users.get_user_time_offline(user.id), one_unit_limit=True)
            )

            # Show off user's level / xp 
            xp = module.users.get_user_xp(user.id)
            level = module.users.get_user_level(user.id)
            levelxp = '**Level {}**   {} / {} XP\n{}'.format(
                level,
                xp,
                module.xp_needed_for_level(level),
                get_progress_bar(xp, module.xp_needed_for_level(level))
            )

            # Get all of the user's roles, highlighting their top role
            if hasattr(user, 'roles'):
                roles = user.roles[1:]
                roles.reverse()
                named_roles = [role.name for role in roles]
                if named_roles:
                    named_roles[0] = '**' + named_roles[0] + '**'
                else:
                    named_roles = ['¯\_(ツ)_/¯']
            else:
                roles = []
                named_roles = ['¯\_(ツ)_/¯']

            embed = module.create_discord_embed(
                action='Lookup',
                primary_info=str(user),
                secondary_info=user.mention,
                thumbnail=user.avatar_url,
                fields=[
                    {'name': 'Account Creation Date', 'value': str(user.created_at.date()), 'inline': True},
                    {'name': 'Join Date', 'value': str(user.joined_at.date()) if hasattr(user, 'joined_at') else 'Not on the server.', 'inline': True},
                    {'name': 'Level / XP', 'value': levelxp, 'inline': True},
                    {
                        'name': 'Roles', 
                        'value': '\n'.join(named_roles),
                        'inline': True
                    },
                    {'name': 'Top 3 Channels', 'value': '\n'.join(messages), 'inline': True},
                    {'name': 'Statuses', 'value': statuses, 'inline': True}
                ] + ([{'name': 'Notes', 'value': '\n\n'.join(notes), 'inline': False}] if notes else []) + punishment_fields,
                footer={'text': "Available Commands: ~editReason | ~removePunishment | ~editNote | ~removeNote"} if punishment_fields else None,
                color=roles[0].color if roles else None
            )
            return embed