def main():
    """Entrypoint when used as an executable
    :returns: None

    """

    # Initialize Logging
    logging.basicConfig(level=logging.DEBUG)
    args = get_commandline_arguments()
    init_logging(args)

    vault = Vault(os.environ["VAULT_ADDR"], args.token)
    secrets = vault.recursive_list(args.engine, args.vaultpath)
    path_depth = 0
    ul_count = 0
    for secret in secrets:
        new_path_depth = secret.count("/")
        if not secret.endswith("/"):
            new_path_depth = new_path_depth + 1
        if new_path_depth > path_depth:
            print("<ul>")
            ul_count = ul_count + 1
        if new_path_depth < path_depth:
            diff = path_depth - new_path_depth
            for _ in range(diff):
                print("</ul>")
            ul_count = ul_count - diff
        path_depth = new_path_depth
        ui_link = vault.path_to_ui_link(args.engine, secret)
        print(html_list_element(html_link(secret, ui_link)))
    for _ in range(ul_count):
        print("</ul>")
示例#2
0
def main():
    """Entrypoint when used as an executable
    :returns: None

    """

    # Initialize Logging
    logging.basicConfig(level=logging.DEBUG)
    args = get_commandline_arguments()
    init_logging(args)

    vault = Vault(os.environ["VAULT_ADDR"], args.token)
    vault.del_userpass_user(args.user)
def main():
    """Entrypoint when used as an executable
    :returns: None

    """

    # Initialize Logging
    logging.basicConfig(level=logging.DEBUG)
    args = get_commandline_arguments()
    init_logging(args)

    vault = Vault(os.environ["VAULT_ADDR"], args.token)
    if args.recursive:
        vault.recursive_delete(args.engine, args.vaultpath)
        return
    vault.delete(args.engine, args.vaultpath)
示例#4
0
def main():
    """Entrypoint when used as an executable
    :returns: None

    """

    # Initialize Logging
    logging.basicConfig(level=logging.DEBUG)
    args = get_commandline_arguments()
    init_logging(args)

    vault = Vault(os.environ["VAULT_ADDR"], args.token)
    password = vault.add_user(args.firstname, args.lastname)
    token = vault.wrap({"password": password})
    unwrap = vault.unwrap_str(token)
    print(unwrap)
    """
    result = []
    my_parser = BibTexParser()
    my_parser.customization = _customizations
    for file_location in locations:
        if file_location.endswith(".bib"):
            with open(file_location) as bib_file:
                try:
                    result.extend(bibtexparser.load(bib_file, parser=my_parser).entries)
                except:
                    logger.error(".bib parsing error: " + file_location)
    return result


def main():
    """
    This is a main procedure only for testing! It shouldn't normally run!
    """
    logger.warning("This is a main procedure only for testing this module! It shouldn't normally run!")
    bib_db = get_all_entries(glob.glob("bibs/*.bib"))
    for dct in bib_db:
        try:
            print(str(dct))
        except UnicodeEncodeError as e:
            logger.error("{}: Entry with id='{}' can't be printed".format(e.reason, dct["ID"]))


if __name__ == "__main__":
    init_logging()
    main()
示例#6
0
from lib.evaluation.sg_eval import BasicSceneGraphEvaluator
from lib.pytorch_misc import print_para
from torch.optim.lr_scheduler import ReduceLROnPlateau
from init_logging import init_logging
import logging
import ipdb

conf = ModelConfig()
if conf.model == 'motifnet':
    from lib.rel_model import RelModel
elif conf.model == 'stanford':
    from lib.rel_model_stanford import RelModelStanford as RelModel
else:
    raise ValueError()

init_logging(conf.save_dir + "/tripscore.log")

train, val, _ = VG.splits(num_val_im=conf.val_size,
                          filter_duplicate_rels=True,
                          use_proposals=conf.use_proposals,
                          filter_non_overlap=conf.mode == 'sgdet')
train_loader, val_loader = VGDataLoader.splits(train,
                                               val,
                                               mode='rel',
                                               batch_size=conf.batch_size,
                                               num_workers=conf.num_workers,
                                               num_gpus=conf.num_gpus)

# ipdb.set_trace()

detector = RelModel(
示例#7
0
import time
import os
from config import ModelConfig, FG_FRACTION, RPN_FG_FRACTION, IM_SCALE, BOX_SCALE
from torch.nn import functional as F
from lib.fpn.box_utils import bbox_loss
import torch.backends.cudnn as cudnn
from pycocotools.cocoeval import COCOeval
from lib.pytorch_misc import optimistic_restore, clip_grad_norm
from torch.optim.lr_scheduler import ReduceLROnPlateau
from init_logging import init_logging
import logging
import ipdb

cudnn.benchmark = True
conf = ModelConfig()
init_logging(conf.save_dir + "/train_detector.log")
if conf.coco:
    train, val = CocoDetection.splits()
    val.ids = val.ids[:conf.val_size]
    train.ids = train.ids
    train_loader, val_loader = CocoDataLoader.splits(
        train,
        val,
        batch_size=conf.batch_size,
        num_workers=conf.num_workers,
        num_gpus=conf.num_gpus)
else:
    #ipdb.set_trace()
    # get into VG classmethod .splits
    train, val, _ = VG.splits(num_val_im=conf.val_size,
                              filter_non_overlap=False,
示例#8
0
#!/usr/bin/env python
#-*-coding: utf-8-*-

# Version: 0.1
# Author: Anson Tang <*****@*****.**>
# License: Copyright(c) 2015 Anson.Tang
# Summary: 

from init_logbook import init_logbook, Log
from init_logging import init_logging, Log

from test_1.test_2.test_log import *

def test():
    Log.error('==========error:{}.'.format('hi, error!'))
    Log.warn('===========warn:{}.'.format('hi, warn!'))
    Log.info('===========info:{}.'.format('hi, info!'))
    Log.debug('==========debug:{}.'.format('hi, debug!'))

if __name__ == "__main__":
    # init logging
    init_logging('./error.log', 'WARNING')
    
    # or init logbook
    #init_logbook('./error.log', 'ERROR')

    test()
def main():
    """the main method"""

    # Initialize logging
    init_logging()

    # Initialize the client
    print("Starting up...")
    client = Bot('!', intents=intents)

    #start webserver
    webserver_thread = threading.Thread(target=run_server,
                                        args=(aiohttp_server(client), ))
    webserver_thread.start()

    # enable slash commands and send them to the discord API
    SlashCommand(client, sync_commands=True)

    # enable buttons
    DiscordComponents(client)

    # load slash command cogs
    # to do that, loop through the files and import all classes and commands
    print("Loading commands...")
    slash_dir = "slash_commands"
    for file in os.listdir(slash_dir):
        if file.endswith(".py"):
            file = file.removesuffix(".py")
            extension = f"{slash_dir}.{file}"
            client.load_extension(extension)

    # pylint: disable=no-member
    print(f"{len(client.slash.commands)} commands loaded")

    # Define event handlers for the client
    # on_ready may be called multiple times in the event of a reconnect,
    @client.event
    async def on_ready():
        if this.running:
            return
        this.running = True
        print("Logged in")

        # run further launch event loops
        await launch_event_loops(client)

    # The message handler for both new message and edits
    @client.event
    async def common_handle_message(message):
        text = message.content

        # if the message was from an dm, post it in #admin-discussions: Don't do that if bot send an command
        if isinstance(message.channel, discord.channel.DMChannel):
            if not message.author.bot:
                if not text.startswith(COMMAND_PREFIX):
                    admin_discussions_channel = client.get_channel(
                        admin_discussions_channel_id)
                    if message.attachments:
                        attached_files = [
                            discord.File(BytesIO(await attachment.read()),
                                         filename=attachment.filename)
                            for attachment in message.attachments
                        ]
                        await admin_discussions_channel.send(
                            f"From {message.author.mention}: \n{text}",
                            files=attached_files)
                    else:
                        await admin_discussions_channel.send(
                            f"From {message.author.mention}: \n{text}")
                    await message.author.send(
                        "Forwarded your message to staff, you will be contacted shortly 🙃"
                    )

        if 'äbidöpfel' in text:
            texts = [
                '<:NeriaHeart:671389916277506063> <:NeriaHeart:671389916277506063> <:NeriaHeart:671389916277506063>',
                'knows what`s up', 'knows you can do the thing',
                'has been voted plushie of the month', 'knows da wey', 'yes!',
                'does`nt yeet teammtes of the map, be like Häbidöpfel',
                'debuggin has proven effective 99.9% of the time (editors note: now 98.9%)',
                'is cuteness incarnate'
            ]
            addition = random.choice(texts)
            await message.channel.send(f'Häbidöpfel {addition}')

        if "welcome" in text.lower() and message.mentions:
            for mention in message.mentions:
                neria_id = 109022023979667456
                if mention.id == neria_id:
                    welcome_choice = [
                        "Welcome",
                        "I mirëpritur",
                        "Dobrodošli",
                        "Vitejte",
                        "Welkom",
                        "Tere tulemast",
                        "Tervetuloa",
                        "Bienvenue",
                        "Herzlich willkommen",
                        "Üdvözöljük",
                        "Velkominn",
                        "Fáilte",
                        "Benvenuta",
                        "Velkommen",
                        "Witamy",
                        "Bine ați venit (this is spelled correctly thanks to <@171371726444167168>)",
                        "Bienvenidas",
                        "Välkommen",
                        "Croeso",
                        "Yeeeeeeeeeeeeeeeeeeeeeeeeeeeeehaw",
                    ]
                    await message.channel.send(
                        f'{random.choice(welcome_choice)} <@{neria_id}>!')

        if client.user in message.mentions:  # If bot has been tagged
            notification = client.get_emoji(
                751771924866269214)  # notification/angerping
            # sentimentPositive = client.get_emoji(670369126983794700) #POGGERS
            # sentimentNegative = client.get_emoji(670672093263822877) #SadChamp
            await message.add_reaction(notification)

        # mute pepe for an hour if he trashes destiny
        if message.author.id == 367385031569702912420:
            if "destiny" in text.lower():
                for insult in ["suck", "bad", "f**k", "shit", "trash"]:
                    if insult in text.lower():
                        # mute pepe and msg him about it
                        await assignRolesToUser([muted_role_id],
                                                message.author, message.guild)
                        await message.author.send(
                            "Stop trashing on destiny, muted for an hour :)")
                        nick = message.author.nick
                        await message.author.edit(
                            nick="!Pepe the Muted for an Hour")

                        # remove muted role after an hour
                        await asyncio.sleep(60 * 60)
                        await removeRolesFromUser([muted_role_id],
                                                  message.author,
                                                  message.guild)
                        await message.author.edit(nick=nick)
                        await message.author.send("Unmuted again :(")
                        return

        # run the command if starts with !
        if text.startswith(COMMAND_PREFIX) and text != COMMAND_PREFIX:
            cmd_split = text[len(COMMAND_PREFIX):].split()
            try:
                await message_handler.handle_command(cmd_split[0].lower(),
                                                     cmd_split[1:], message,
                                                     client)
            except:
                print("Error while handling message", flush=True)
                raise
        else:
            badwords = [
                'kanen', 'cyber', 'dicknugget', 'nigg', 'cmonbrug', ' bo ',
                'bloodoak', 'ascend', 'c**k', 'c**t'
            ]
            goodchannels = [
                670400011519000616,  # general
                670400027155365929,  # media
                670402166103474190,  # spoiler-chat
                670362162660900895,  # off-topic
                # 672541982157045791 #markov-chat-channel
            ]
            if not message.content.startswith('http') and len(
                    message.clean_content) > 5 and not any([
                        badword in message.clean_content.lower()
                        for badword in badwords
                    ]) and message.channel.id in goodchannels:
                await insertIntoMessageDB(message.clean_content,
                                          message.author.id,
                                          message.channel.id, message.id)

        if message.author.name == 'EscalatorBot':
            for user in message.mentions:
                member = await message.guild.fetch_member(user.id)
                await member.add_roles(
                    message.guild.get_role(registered_role_id)
                )  # registered role
                await member.remove_roles(
                    message.guild.get_role(not_registered_role_id)
                )  # unregistered role
                await message.channel.send(
                    f'{member.mention} has been marked as Registered')
                await member.send(
                    'Registration successful!\nCome say hi in <#670400011519000616>'
                )

                # update user DB
                destinyID = await lookupDestinyID(member.id)
                await updateDB(destinyID)

    @client.event
    async def on_message(message):
        # ignore msg from itself
        if (message.author == client.user):
            return
        asyncio.ensure_future(common_handle_message(message))

    @client.event
    async def on_member_join(member):
        # inform the user that they should register with the bot
        await member.send(embed=embed_message(
            f'Welcome to Descend {member.name}!',
            'You can join the destiny clan in **#registration**. \nYou can find our current requirements in the same channel. \n⁣\nWe have a wide variety of roles you can earn, for more information, check out #community-roles. \n⁣\nIf you have any problems / questions, do not hesitate to write **@ElevatorBot** (me) a personal message with your problem / question'
        ))

    @client.event
    async def on_member_remove(member):
        await removeFromClanAfterLeftDiscord(client, member)

    @client.event
    async def on_message_edit(before, after):
        await common_handle_message(after)

    # https://discordpy.readthedocs.io/en/latest/api.html#discord.RawReactionActionEvent
    @client.event
    async def on_raw_reaction_add(payload):
        if not payload.member or payload.member.bot:
            return

        # check if reaction is on a persistent message
        await check_reaction_for_persistent_message(client, payload)

    @client.event
    async def on_voice_state_update(member, before, after):
        guild = member.guild
        lfg_voice_category_channel = await get_persistent_message_or_channel(
            client, "lfgVoiceCategory", guild.id)

        if before.channel is None:
            # print(f'{member.name} joined VC {after.channel.name}')
            await joined_channel(client, member, after.channel)
            return

        if after.channel is None:
            # print(f'{member.name} left VC {before.channel.name}')
            await left_channel(client, member, before.channel, after.channel,
                               lfg_voice_category_channel)
            return

        if before.channel != after.channel:
            # print(f'{member.name} changed VC from {before.channel.name} to {after.channel.name}')
            await joined_channel(client, member, after.channel)
            await left_channel(client, member, before.channel, after.channel,
                               lfg_voice_category_channel)
            return

    @client.event
    async def on_member_update(before, after):
        """ Add member role after Role Screening """

        if before.bot or after.bot:
            return
        if before.pending and not after.pending:
            member = client.get_guild(before.guild.id).get_member(before.id)

            # add @member
            await assignRolesToUser([member_role_id], member, member.guild)

            # add @Not Registered to user
            await assignRolesToUser([not_registered_role_id], member,
                                    member.guild)

            # add filler roles
            await assignRolesToUser([divider_raider_role_id], member,
                                    member.guild)
            await assignRolesToUser([divider_achievement_role_id], member,
                                    member.guild)
            await assignRolesToUser([divider_misc_role_id], member,
                                    member.guild)

    @client.event
    async def on_slash_command(ctx: SlashContext):
        """ Gets triggered every slash command """

        # print the command
        print(
            f"{ctx.author.display_name} used '/{ctx.name}' with kwargs '{ctx.kwargs}'"
        )

        # log the command
        logger = logging.getLogger('slash_commands')
        logger.info(
            f"InteractionID '{ctx.interaction_id}' - User '{ctx.author.name}' with discordID '{ctx.author.id}' executed '/{ctx.name}' with kwargs '{ctx.kwargs}' in guildID '{ctx.guild.id}', channelID '{ctx.channel.id}'"
        )

    @client.event
    async def on_slash_command_error(ctx: SlashContext, error: Exception):
        """ Gets triggered on slash errors """

        await ctx.send(embed=embed_message(
            "Error",
            f"Sorry, something went wrong \nPlease contact a {ctx.guild.get_role(dev_role_id)}",
            error))

        # log the error
        logger = logging.getLogger('slash_commands')
        logger.exception(
            f"InteractionID '{ctx.interaction_id}' - Error {error} - Traceback: \n{''.join(traceback.format_tb(error.__traceback__))}"
        )

        # raising error again to making deving easier
        raise error

    @client.event
    async def on_button_click(interaction: discord_components.Context):
        # look if they are lfg buttons
        if interaction.component.id.startswith("lfg"):
            # get the lfg message
            lfg_message = await get_lfg_message(
                client=interaction.bot,
                lfg_message_id=interaction.message.id,
                guild=interaction.guild)

            if interaction.component.label == "Join":
                res = await lfg_message.add_member(
                    member=interaction.guild.get_member(interaction.author.id))
                if res:
                    await interaction.respond(type=6)
                else:
                    await interaction.respond(
                        type=discord_components.InteractionType.
                        ChannelMessageWithSource,
                        embed=embed_message(
                            "Error",
                            "You could not be added to the event\nThis is either because you are already in the event, the event is full, or the creator has blacklisted you from their events"
                        ))

            if interaction.component.label == "Leave":
                res = await lfg_message.remove_member(
                    member=interaction.guild.get_member(interaction.author.id))
                if res:
                    await interaction.respond(type=6)
                else:
                    await interaction.respond(
                        type=discord_components.InteractionType.
                        ChannelMessageWithSource,
                        embed=embed_message(
                            "Error",
                            "You could not be removed from the event\nThis is because you are neither in the main nor in the backup roster"
                        ))

            if interaction.component.label == "Backup":
                res = await lfg_message.add_backup(
                    member=interaction.guild.get_member(interaction.author.id))
                if res:
                    await interaction.respond(type=6)
                else:
                    await interaction.respond(
                        type=discord_components.InteractionType.
                        ChannelMessageWithSource,
                        embed=embed_message(
                            "Error",
                            "You could not be added as a backup to the event\nThis is either because you are already in the backup roster, or the creator has blacklisted you from their events"
                        ))

    # Finally, set the bot running
    client.run(BOT_TOKEN)
import json

import click
import asyncio
import aiohttp_cors
from aiohttp import web
from pip._internal.utils import logging

from init_logging import init_logging
from world.creatures.player import Player
from world.world import World

init_logging('debug')

logger = logging.getLogger(__name__)


async def handle(request):
    return web.Response(body='nothing', content_type='text/html')


async def remove_player(app, player):
    logger.info('%s disconnected, closing socket' % player)
    await player.websocket.close()

    logger.info('removing player %s from world' % player)
    app['world'].remove_player(player)

    logger.info('removing player %s from app' % player)
    app['players'].remove(player)
from lib.evaluation.sg_eval import BasicSceneGraphEvaluator
from lib.pytorch_misc import print_para
from torch.optim.lr_scheduler import ReduceLROnPlateau
from init_logging import init_logging
import logging
import ipdb

conf = ModelConfig()
if conf.model == 'motifnet':
    from lib.rel_model import RelModel
elif conf.model == 'stanford':
    from lib.rel_model_stanford import RelModelStanford as RelModel
else:
    raise ValueError()

init_logging(conf.save_dir + "/distance.log")

train, val, _ = VG.splits(num_val_im=conf.val_size,
                          filter_duplicate_rels=True,
                          use_proposals=conf.use_proposals,
                          filter_non_overlap=conf.mode == 'sgdet')
train_loader, val_loader = VGDataLoader.splits(train,
                                               val,
                                               mode='rel',
                                               batch_size=conf.batch_size,
                                               num_workers=conf.num_workers,
                                               num_gpus=conf.num_gpus)

# ipdb.set_trace()

detector = RelModel(
示例#12
0
import pandas as pd
import numpy as np 
import datetime as dt
import yfinance as yf
import random
from time import sleep
import io
import os
import logging


import init_logging as il
import help_functions as hf

# SET UP LOGGING
il.init_logging()



# set up parameters
#swe_holidays = holidays.Sweden()

STOCKMARKET_CLOSES = hf.STOCKMARKET_CLOSES
WAITFORMARKET = hf.WAITFORMARKET
START_DATE = hf.START_DATE


# check if stock market has closed
date_today = dt.date.today()
datetime_today = dt.datetime.today()
timeconstraint = dt.datetime.combine(date_today,STOCKMARKET_CLOSES) + dt.timedelta(minutes=WAITFORMARKET)
示例#13
0
import datetime
import logging

from init_logging import init_logging
from discord.ext import commands
from pathlib import Path
from Database import Database
from parse_args import parse_args

# Parse command-line for custom settings, such as changing the default prefix and enabling the dev mode to enable
# error messages.
args = parse_args()

# initialize logging
level = logging.DEBUG if args.dev else logging.INFO
log = init_logging("MULTI_RPG", level)

# Bot's prefix is defaulted to '='.
bot_prefix = "="

# Command error handling
enable_error = True

# if --dev mode, enable error
if args.dev:
    bot_prefix = "."
    enable_error = False
    log.info(f"Running dev mode. enable_error = {enable_error}")

# Check if a prefix was passed, so we override the prefix set by args.dev
if args.prefix: