예제 #1
0
 def test_single_part(self):
     expected = {
         "one": 1,
         "two": 2,
         "three": 3,
         "four": 4,
         "five": 5,
         "six": 6,
         "seven": 7,
         "eight": 8,
         "nine": 9,
         "ten": 10,
         "eleven": 11,
         "twelve": 12,
         "thirteen": 13,
         "fourteen": 14,
         "fifteen": 15,
         "sixteen": 16,
         "seventeen": 17,
         "eighteen": 18,
         "nineteen": 19,
         "twenty": 20,
         "thirty": 30,
         "forty": 40,
         "fifty": 50,
         "sixty": 60,
         "seventy": 70,
         "eighty": 80,
         "ninety": 90,
     }
     for test in expected:
         self.assertEqual(get(test), '"' + test + '" parses to ' + str(expected[test]))
예제 #2
0
 def __init__(self, *args, **kwargs):
     super().__init__(
         help_command=commands.DefaultHelpCommand(dm_help=True),
         *args,
         **kwargs)
     self.config = lib.get('./settings.json')
     self.start_time = time.time()
     self.app_info = None
     self.setup()
예제 #3
0
    def update(self):
        """
        Run any database updates which are required
        :return:
        """
        db = Database.instance()

        version = lib.get('./version.json')
        version = version.db_version

        db_version = db.get('bot_settings', {'setting': 'version'})
        current_version = db_version['value'] if db_version else 0

        version = int(version)
        current_version = int(current_version)

        # Find all update files
        for file in os.listdir(f'data/updates'):

            # If it ends with .update then try to use it.
            if file.endswith(".update"):

                # Get the update version from the file name and convert to int for comparison.
                update_version = int(file[:-7])

                # Is this update due to run?
                if update_version > current_version:

                    # Load the file and the SQL to run.
                    update = lib.get('./data/updates/' + file)

                    # Loop through the array of SQL statements to run.
                    for sql in update:
                        lib.out('[UPDATE] Running query `' + sql + '`')
                        db.execute(sql, [])

        # Once it's done, update the version in the database.
        setting = db.get('bot_settings', {'setting': 'version'})
        if setting:
            db.update('bot_settings', {'value': version},
                      {'setting': 'version'})
        else:
            db.insert('bot_settings', {'setting': 'version', 'value': version})
예제 #4
0
파일: cursestest.py 프로젝트: ivanguy/chat
def chooser(stdscr):
    nicks, ips = get()
    curses.cbreak()
    stdscr.scrollok(True)
    while True:
        global key
        key = stdscr.getkey()
        stdscr.addstr(str(key))
        stdscr.refresh()
        break
    curses.endwin()
예제 #5
0
파일: cursestest.py 프로젝트: ivanguy/chat
def chooser(stdscr):
    nicks, ips = get()
    curses.cbreak()
    stdscr.scrollok(True)
    while True:
        global key
        key = stdscr.getkey()
        stdscr.addstr(str(key))
        stdscr.refresh()
        break
    curses.endwin()
예제 #6
0
    def calibrations(self, pars, which='mn', calSlice=(None,None), N=1000, label='', **kwargs):

        sampleList = [c['sample'] for c in calibration_specs() if c['which']==which]
        prePre = pars['dirIncrement'] in [0,4,5]

        args = {
            'signal':pars['signal'],
            'sigPrefix':pars['sigPre'],
            'dirPrefix':"R%02d" % (pars['R0_'] + pars['dirIncrement']),
            'genDirPre':pars['genDirPre'],
            'prePre':prePre,
            'templateID':None,
            'hackZeroBins':pars['hackZeroBins'] and 'QCD'==part,
            'sampleList': sampleList
            }
        alt_channels = dict( [ ((lep,part), inputs.channel_data(lep, part, **args))
                               for lep in ['el','mu'] for part in ['top','QCD']] )

        # get Ac_phi_ttalt and Ac_y_ttalt
        filePattern = 'data/stats_top_mu_%s.root'
        tag = 'ph_sn_jn_20'
        tfile = r.TFile.Open(filePattern%tag)
        h = lib.get(tfile,'genTopTanhDeltaAbsY_genTopDPtDPhi/'+ sampleList[0])
        Ac_y_ttalt = lib.asymmetry(h.ProjectionX())[0]
        Ac_phi_ttalt = lib.asymmetry(h.ProjectionY())[0]
        tfile.Close()

        model = self.central.model
        model.import_alt_model(alt_channels)
        wGen = model.w

        # bring xs_ttalt to the most consistant value possible
        wGen.arg('d_xs_ttalt').setVal((wGen.arg('expect_mu_tt').getVal() + wGen.arg('expect_el_tt').getVal()) /
                                      (wGen.arg('expect_mu_ttalt').getVal() + wGen.arg('expect_el_ttalt').getVal()) - 1)
        # not clear how to do the same for factor_*_qcd (equivalent bg representations)

        truth = dict([(s,eval(s)) for s in ['Ac_y_ttalt','Ac_phi_ttalt']])
        altItems = ['expect_%s_ttalt'%s for s in ['el','mu']]
        for item in (set(fit.modelItems()+altItems)-set(fit.altmodelNonItems())): truth[item] = wGen.arg(item).getVal()

        mcstudy = r.RooMCStudy(wGen.pdf('altmodel'),
                               wGen.argSet(','.join(model.observables+['channel'])),
                               r.RooFit.Binned(True),
                               r.RooFit.Extended(True)
                           )
        mcstudy.generate(N,0,True)
        for i in range(N)[slice(*calSlice)]:
            alt = mcstudy.genData(i)
            pars['label'] = '%s_cal%s%03d'%(label,which,i)
            with open(self.outNameBase + pars['label'] + '.log', 'w') as log:
                pars['log']=log
                f = fit(altData=alt, **pars)
            f.ttreeWrite(self.outNameBase + pars['label'] + '.root', truth)
예제 #7
0
    async def invite(self, context):
        """
        Displays an embed with and invite link
        """
        config = lib.get('./settings.json')
        invite_embed = discord.Embed(title='Invite Link',
                                     color=652430,
                                     url=config.invite_url)
        invite_embed.add_field(
            name='Click the title for the invite link!',
            value="Use the Above link to invite the bot to your servers!")

        await context.send(embed=invite_embed)
예제 #8
0
    def __init__(self):

        self.__path = os.path.abspath(os.path.dirname(__file__))

        # Load the connection configuration
        config = lib.get(self.__path + '/../settings.json')
        self.connection = pymysql.connect(host=config.db_host,
                                          user=config.db_user,
                                          passwd=config.db_pass,
                                          db=config.db_name,
                                          autocommit=True)

        # Set the cursor to be used, with DictCursor so we can refer to results by their keys
        self.cursor = self.connection.cursor(pymysql.cursors.DictCursor)
예제 #9
0
 def test_complex_nums(self):
     expected = {
         "two billion, seven hundred and three thousand, two hundred and forty-seven": 2000703247,
         "two million billion": 2000000000000000,
         "two million billion and seven": 2000000000000007,
         "forty-seven thousand": 47000,
         "forty-two million, forty-three thousand": 42043000,
         "twenty-seven thousand, four hundred and twenty-two": 27422,
         "seven million, four hundred thousand": 7400000,
         "two hundred thousand, four hundred and twenty-seven": 200427,
         "three hundred and forty-seven million, three hundred and forty-seven thousand, three hundred and forty-seven": 347347347,
         "three hundred and eighty-three": 383,
         "one million, seven hundred and thirteen thousand, nine hundred and eighty-two": 1713982,
         "seven hundred and two vigintillion": 702000000000000000000000000000000000000000000000000000000000000000,
         "one novemdecillion, three quintillion sextillion": 1000000000000000000003000000000000000000000000000000000000000,
         "four million, two hundred and seven thousand trillion": 4207000000000000000,
     }
     for test in expected:
         self.assertEqual(get(test), '"' + test + '" parses to ' + str(expected[test]))
예제 #10
0
    def load_prefix(bot, message):
        """
        Get the prefix to use for the guild
        :param bot:
        :param message:
        :return:
        """
        db = Database.instance()
        prefixes = {}
        config = lib.get('./settings.json')

        # Get the guild_settings for prefix and add to a dictionary, with the guild id as the key.
        settings = db.get_all('guild_settings', {'setting': 'prefix'})
        for setting in settings:
            prefixes[int(setting['guild'])] = setting['value']

        # If the guild id exists in this dictionary return that, otherwise return the default.
        if message.guild is not None:
            return prefixes.get(message.guild.id, config.prefix)
        else:
            return config.prefix
예제 #11
0
    def get_leaderboard(self, limit=None):
        """
        Build the embedded leaderboard to display
        :return:
        """

        config = lib.get('./settings.json')
        users = self.get_users()

        # Build the embedded leaderboard message
        title = self.get_title() + ' ' + lib.get_string(
            'event:leaderboard', self.get_guild())
        description = lib.get_string('event:leaderboard:desc',
                                     self.get_guild()).format(
                                         limit, self.get_title())
        footer = lib.get_string('event:leaderboard:footer',
                                self.get_guild()).format(limit)

        # If there is no limit, don't show the footer
        if limit is None:
            footer = None

        # If the event is finished, don't show the footer and adjust the description to take out 'so far'
        if self.is_ended():
            description = lib.get_string('event:leaderboard:desc:ended',
                                         self.get_guild()).format(
                                             self.get_title())
            footer = None

        image = self.get_image()
        if not image or len(image) == 0:
            image = config.avatar

        embed = discord.Embed(title=title,
                              color=self.get_colour(),
                              description=description)
        embed.set_thumbnail(url=image)
        if footer:
            embed.set_footer(text=footer, icon_url=config.avatar)

        # Add users
        position = 1

        for user in users:

            # Get the user and pass in the bot, so we can get their guild nickname
            user_object = User(user['user'],
                               self.get_guild(),
                               context=self.__context,
                               bot=self.__bot)

            # Easiest way to check if the user is still a member of the guild, is to see if we can get their nickname
            if user_object.is_guild_member():

                # Build the name and words variables to display in the list
                name = str(position) + '. ' + user_object.get_name()
                words = str(user['words'])

                # Embed this user result as a field
                embed.add_field(name=name, value=words, inline=False)

                # Increment position
                position += 1

        return embed
예제 #12
0
 def get(s, ps):
     return next(
         iter(filter(None, [lib.get(tfile, p + s) for p in ps])), None)
예제 #13
0
#!/usr/bin/env python3
import discord, json, lib
from bot import WriterBot
from discord.ext import commands
from pprint import pprint

# Load the settings for initial setup
config = lib.get('./settings.json')

# Load the Bot object
status = discord.Game('Booting up...')
bot = WriterBot(command_prefix=WriterBot.load_prefix, activity=status)

# Load all commands
bot.load_commands()

# Start the bot
bot.run(config.token)
예제 #14
0
#!/usr/bin/env python
import os, sys;
from lib import get;

if sys.version_info[0] < 3:
	print('This application was designed to run for Python3. Get out');
	exit();

#if specified in argv, print and exit
if (len(sys.argv) > 1):
	if (sys.argv[1] == 'test'):
		os.system('./test.py');
		exit();
	print(get(sys.argv[1]));
	exit();

#else print welcome stuff and start the loop
os.system(['clear','cls'][os.name == 'nt']);
print('\033[1mWelcome to numbers.py!\033[0;0m\n');
print('This script attempts to convert numbers from word form to proper numbers.');
print('It is an experiment, so don\'t expect it to work properly.\n');


try:
	while True:
		string = input('Please enter a string to convert to a number: ');
		if (string == 'exit'):
			print('\nThanks for using numbers.py\n\n');
			exit();

		print(get(string) + '\n');
예제 #15
0
    async def help(self, context, command="help"):
        """
        Help command and subcommands
        """

        user = User(context.message.author.id, context.guild.id, context)

        command = command.lower()

        config = lib.get('./settings.json')

        if command == "help":

            url = config.src + '/wiki/Commands' if config.src != "" else None

            help_embed = discord.Embed(
                title="Help with Writer Bot",
                description="For more help with a command run `help [command]`",
                color=discord.Color.blurple(),
                url=url)
            help_embed.add_field(name='`about`',
                                 value=lib.get_string('help:about',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`ask`',
                                 value=lib.get_string('help:ask',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`challenge`',
                                 value=lib.get_string('help:challenge',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`8ball`',
                                 value=lib.get_string('help:8ball',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`event`',
                                 value=lib.get_string('help:event',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`flip`',
                                 value=lib.get_string('help:flip',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`goal`',
                                 value=lib.get_string('help:goal',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`mysetting`',
                                 value=lib.get_string('help:mysetting',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`ping`',
                                 value=lib.get_string('help:ping',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`profile`',
                                 value=lib.get_string('help:profile',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`project`',
                                 value=lib.get_string('help:project',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`quote`',
                                 value=lib.get_string('help:quote',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`reassure`',
                                 value=lib.get_string('help:reassure',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`reset`',
                                 value=lib.get_string('help:reset',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`remind`',
                                 value=lib.get_string('help:remind',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`roll`',
                                 value=lib.get_string('help:roll',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`sprint`',
                                 value=lib.get_string('help:sprint',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`wrote`',
                                 value=lib.get_string('help:wrote',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`xp`',
                                 value=lib.get_string('help:xp',
                                                      user.get_guild()),
                                 inline=True)
            help_embed.add_field(name='`help`',
                                 value=lib.get_string('help:help',
                                                      user.get_guild()),
                                 inline=True)

            return await context.send(embed=help_embed)

        elif command == 'about':
            about_embed = discord.Embed(title="Help with `about` command.",
                                        color=3897943)
            about_embed.add_field(name="`about`",
                                  value=lib.get_string("help:aboutSub",
                                                       user.get_guild()),
                                  inline=True)

            return await context.send(embed=about_embed)

        elif command == 'ask':
            ask_embed = discord.Embed(title="Help with `ask` command.",
                                      color=3897943)
            ask_embed.add_field(name='`ask char`',
                                value=lib.get_string('help:askCharSub',
                                                     user.get_guild()),
                                inline=True)
            ask_embed.add_field(name='`ask world`',
                                value=lib.get_string('help:askWorldSub',
                                                     user.get_guild()),
                                inline=True)
            ask_embed.set_footer(
                text=lib.get_string('help:askFooter', user.get_guild()))

            return await context.send(embed=ask_embed)

        elif command == 'challenge':
            challenge_embed = discord.Embed(
                title="Help with `challenge` command.", color=3897943)
            challenge_embed.add_field(name='`challenge`',
                                      value=lib.get_string(
                                          'help:challengeSub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.add_field(name='`challenge easy`',
                                      value=lib.get_string(
                                          'help:challengeEasySub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.add_field(name='`challenge normal`',
                                      value=lib.get_string(
                                          'help:challengeNormalSub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.add_field(name='`challenge hard`',
                                      value=lib.get_string(
                                          'help:challengeHardSub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.add_field(name='`challenge hardcore`',
                                      value=lib.get_string(
                                          'help:challengeHardcoreSub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.add_field(name='`challenge insane`',
                                      value=lib.get_string(
                                          'help:challengeInsaneSub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.add_field(name='`challenge 10wpm`',
                                      value=lib.get_string(
                                          'help:challenge10wpmSub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.add_field(name='`challenge 15m`',
                                      value=lib.get_string(
                                          'help:challenge15Sub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.add_field(name='`challenge normal 18m`',
                                      value=lib.get_string(
                                          'help:challengeNormal18Sub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.add_field(name='`challenge cancel`',
                                      value=lib.get_string(
                                          'help:challengeCancelSub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.add_field(name='`challenge complete`',
                                      value=lib.get_string(
                                          'help:challengeCompleteSub',
                                          user.get_guild()),
                                      inline=True)
            challenge_embed.set_footer(
                text=lib.get_string('help:challengeFooter', user.get_guild()))

            return await context.send(embed=challenge_embed)

        elif command == '8ball':
            ball_embed = discord.Embed(title='Help with `8ball` command.',
                                       color=3897943)
            ball_embed.add_field(name='`8ball`',
                                 value=lib.get_string('help:8ballSub',
                                                      user.get_guild()),
                                 inline=True)

            return await context.send(embed=ball_embed)

        elif command == 'event':
            event_embed = discord.Embed(title="Help with `event` command.",
                                        color=3897943)
            event_embed.add_field(name='`event create My event title`',
                                  value=lib.get_string('help:eventCreateSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(name='`event rename My New event title`',
                                  value=lib.get_string('help:eventRenameSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(
                name='`event description This is the description`',
                value=lib.get_string('help:eventDescSub', user.get_guild()),
                inline=True)
            event_embed.add_field(
                name='`event image https://i.imgur.com/tJtAdNs.png`',
                value=lib.get_string('help:eventImageSub', user.get_guild()),
                inline=True)
            event_embed.add_field(name='`event delete`',
                                  value=lib.get_string('help:eventDeleteSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(name='`event schedule`',
                                  value=lib.get_string('help:eventScheduleSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(name='`event unschedule`',
                                  value=lib.get_string('help:eventUnSchSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(name='`event start`',
                                  value=lib.get_string('help:eventStartSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(name='`event end`',
                                  value=lib.get_string('help:eventEndSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(name='`event time`',
                                  value=lib.get_string('help:eventTimeSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(name='`event update 500`',
                                  value=lib.get_string('help:eventUpdateSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(name='`event me`',
                                  value=lib.get_string('help:eventMeSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(name='`event top`',
                                  value=lib.get_string('help:eventTopSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.add_field(name='`event info`',
                                  value=lib.get_string('help:eventInfoSub',
                                                       user.get_guild()),
                                  inline=True)
            event_embed.set_footer(
                text=lib.get_string('help:eventFooter', user.get_guild()))

            return await context.send(embed=event_embed)

        elif command == 'flip':
            flip_embed = discord.Embed(title="Help with `flip` command.",
                                       color=3897943)
            flip_embed.add_field(name='`flip`',
                                 value=lib.get_string('help:flipSub',
                                                      user.get_guild()),
                                 inline=True)

            return await context.send(embed=flip_embed)

        elif command == 'generate':
            gen_embed = discord.Embed(title="Help with `generate` command.",
                                      color=3897943)
            gen_embed.add_field(name='`generate char`',
                                value=lib.get_string('help:generateCharSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate place`',
                                value=lib.get_string('help:generatePlaceSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate land`',
                                value=lib.get_string('help:generateLandSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate book`',
                                value=lib.get_string('help:generateBookSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate book_fantasy`',
                                value=lib.get_string('help:generateBookFanSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate book_sf`',
                                value=lib.get_string('help:generateBookSFSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate book_horror`',
                                value=lib.get_string(
                                    'help:generateBookHorrorSub',
                                    user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate book_rom`',
                                value=lib.get_string('help:generateBookRomSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate book_mystery`',
                                value=lib.get_string('help:generateBookMysSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate book_hp`',
                                value=lib.get_string('help:generateBookHPSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate idea`',
                                value=lib.get_string('help:generateIdeaSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate prompt`',
                                value=lib.get_string('help:generatePromptSub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate place 20`',
                                value=lib.get_string('help:generatePlace20Sub',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.add_field(name='`generate face`',
                                value=lib.get_string('help:generateFace',
                                                     user.get_guild()),
                                inline=True)
            gen_embed.set_footer(
                text=lib.get_string('help:generateFooter', user.get_guild()))

            return await context.send(embed=gen_embed)

        elif command == 'goal':
            goal_embed = discord.Embed(title='Help with `goal` command.',
                                       color=3897943)
            goal_embed.add_field(name='`goal`',
                                 value=lib.get_string('help:goalSub',
                                                      user.get_guild()),
                                 inline=True)
            goal_embed.add_field(name='`goal check daily`',
                                 value=lib.get_string('help:goalCheckSub',
                                                      user.get_guild()),
                                 inline=True)
            goal_embed.add_field(name='`goal set weekly 500`',
                                 value=lib.get_string('help:goalSetSub',
                                                      user.get_guild()),
                                 inline=True)
            goal_embed.add_field(name='`goal cancel monthly`',
                                 value=lib.get_string('help:goalCancelSub',
                                                      user.get_guild()),
                                 inline=True)
            goal_embed.add_field(name='`goal time yearly`',
                                 value=lib.get_string('help:goalTimeSub',
                                                      user.get_guild()),
                                 inline=True)
            goal_embed.add_field(name='`goal history monthly`',
                                 value=lib.get_string('help:goalHistorySub',
                                                      user.get_guild()),
                                 inline=True)
            goal_embed.add_field(name='`goal update yearly 12350`',
                                 value=lib.get_string('help:goalUpdateSub',
                                                      user.get_guild()),
                                 inline=True)

            return await context.send(embed=goal_embed)

        elif command == 'mysetting' or command == 'myset':
            setting_embed = discord.Embed(
                title='Help with `mysetting` command.',
                color=3897943,
                url=lib.get_string('help:mysettingUrlSub', user.get_guild()))
            setting_embed.add_field(
                name='`mysetting timezone America/New_York`',
                value=lib.get_string('help:mysettingTzSub', user.get_guild()),
                inline=True)
            setting_embed.set_footer(
                text=lib.get_string('help:mysetting:footer', user.get_guild()))

            return await context.send(embed=setting_embed)

        elif command == 'ping':
            ping_embed = discord.Embed(title='Help with `ping` command.',
                                       color=3897943)
            ping_embed.add_field(name='`ping`',
                                 value=lib.get_string('help:pingSub',
                                                      user.get_guild()),
                                 inline=True)

            return await context.send(embed=ping_embed)

        elif command == 'profile':
            profile_embed = discord.Embed(title='Help with `profile` command.',
                                          color=3897943)
            profile_embed.add_field(name='`profile`',
                                    value=lib.get_string(
                                        'help:profileSub', user.get_guild()),
                                    inline=True)

            return await context.send(embed=profile_embed)

        elif command == 'project':
            project_embed = discord.Embed(title='Help with `project` command.',
                                          color=3897943)
            project_embed.add_field(
                name='`project create sword The Sword in the Stone`',
                value=lib.get_string('help:projectCreateSub',
                                     user.get_guild()),
                inline=True)
            project_embed.add_field(name='`project delete sword`',
                                    value=lib.get_string(
                                        'help:projectDeleteSub',
                                        user.get_guild()),
                                    inline=True)
            project_embed.add_field(
                name='`project rename sword sword2 The Sword in the Stone Two`',
                value=lib.get_string('help:projectRenameSub',
                                     user.get_guild()),
                inline=False)
            project_embed.add_field(name='`project update sword 6500`',
                                    value=lib.get_string(
                                        'help:projectUpdateSub',
                                        user.get_guild()),
                                    inline=True)
            project_embed.add_field(name='`project list`',
                                    value=lib.get_string(
                                        'help:projectListSub',
                                        user.get_guild()),
                                    inline=True)
            project_embed.add_field(name='`project view sword`',
                                    value=lib.get_string(
                                        'help:projectViewShortnameSub',
                                        user.get_guild()),
                                    inline=True)
            project_embed.add_field(name='`project status sword finished`',
                                    value=lib.get_string(
                                        'help:projectStatusSub',
                                        user.get_guild()),
                                    inline=True)
            project_embed.add_field(name='`project genre sword fantasy`',
                                    value=lib.get_string(
                                        'help:projectGenreSub',
                                        user.get_guild()),
                                    inline=True)
            project_embed.add_field(
                name='`project link sword http://yourwebsite.com/your-book`',
                value=lib.get_string('help:projectLinkSub', user.get_guild()),
                inline=True)
            project_embed.add_field(
                name=
                '`project image sword http://yourwebsite.com/your-image.png`',
                value=lib.get_string('help:projectImageSub', user.get_guild()),
                inline=True)
            project_embed.add_field(
                name=
                '`project description sword Boy finds sword. Boy becomes king.`',
                value=lib.get_string('help:projectDescSub', user.get_guild()),
                inline=True)

            return await context.send(embed=project_embed)

        elif command == 'quote':
            quote_embed = discord.Embed(title='Help with `quote` command.',
                                        color=387943)
            quote_embed.add_field(name='`quote`',
                                  value=lib.get_string('help:quoteSub',
                                                       user.get_guild()),
                                  inline=True)

            return await context.send(embed=quote_embed)

        elif command == 'reassure':
            reassure_embed = discord.Embed(
                title='Help with `reassure` command.', color=3897943)
            reassure_embed.add_field(name='`reassure`',
                                     value=lib.get_string(
                                         'help:reassureSub', user.get_guild()),
                                     inline=True)
            reassure_embed.add_field(name='`reassure @CMR`',
                                     value=lib.get_string(
                                         'help:reassureUserSub',
                                         user.get_guild()),
                                     inline=True)

            return await context.send(embed=reassure_embed)

        elif command == 'reset':
            reset_embed = discord.Embed(title='Help with `reset` command.',
                                        color=3897943)
            reset_embed.add_field(name='`reset pb`',
                                  value=lib.get_string('help:resetPbSub',
                                                       user.get_guild()),
                                  inline=True)
            reset_embed.add_field(name='`reset wc`',
                                  value=lib.get_string('help:resetWcSub',
                                                       user.get_guild()),
                                  inline=True)
            reset_embed.add_field(name='`reset xp`',
                                  value=lib.get_string('help:resetXpSub',
                                                       user.get_guild()),
                                  inline=True)
            reset_embed.add_field(name='`reset projects`',
                                  value=lib.get_string('help:reset:projects',
                                                       user.get_guild()),
                                  inline=True)
            reset_embed.add_field(name='`reset all`',
                                  value=lib.get_string('help:resetAllSub',
                                                       user.get_guild()),
                                  inline=True)

            return await context.send(embed=reset_embed)

        elif command == 'roll':
            roll_embed = discord.Embed(title='Help with `roll` command.',
                                       color=3897943)
            roll_embed.add_field(name='`roll`',
                                 value=lib.get_string('help:rollSub',
                                                      user.get_guild()),
                                 inline=True)
            roll_embed.add_field(name='`roll 1d8`',
                                 value=lib.get_string('help:roll8Sub',
                                                      user.get_guild()),
                                 inline=True)
            roll_embed.add_field(name='`roll 3d20`',
                                 value=lib.get_string('help:roll3d20Sub',
                                                      user.get_guild()),
                                 inline=True)

            return await context.send(embed=roll_embed)

        elif command == 'sprint':
            sprint_embed = discord.Embed(title='Help with `sprint` Command.',
                                         color=3897943)
            sprint_embed.add_field(name='`sprint start`',
                                   value=lib.get_string(
                                       'help:sprintStartSub',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint for 20 in 3`',
                                   value=lib.get_string(
                                       'help:sprint20in3Sub',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint for 20 at .30`',
                                   value=lib.get_string(
                                       'help:sprintForAt', user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint cancel`',
                                   value=lib.get_string(
                                       'help:sprintCancelSub',
                                       user.get_guild()),
                                   inline=False)
            sprint_embed.add_field(name='`sprint join`',
                                   value=lib.get_string(
                                       'help:sprintJoinSub', user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint join 100`',
                                   value=lib.get_string(
                                       'help:sprintJoin100Sub',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint join 100 sword`',
                                   value=lib.get_string(
                                       'help:sprintJoin100SwordSub',
                                       user.get_guild()),
                                   inline=False)
            sprint_embed.add_field(name='`sprint join edit`',
                                   value=lib.get_string(
                                       'help:sprintJoinEdit',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint join same`',
                                   value=lib.get_string(
                                       'help:sprintJoinSame',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint leave`',
                                   value=lib.get_string(
                                       'help:sprintLeaveSub',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint project sword`',
                                   value=lib.get_string(
                                       'help:sprintProjectSwordSub',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint time`',
                                   value=lib.get_string(
                                       'help:sprintTimeSub', user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint wc 250`',
                                   value=lib.get_string(
                                       'help:sprintWc250Sub',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint pb`',
                                   value=lib.get_string(
                                       'help:sprintPbSub', user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint notify`',
                                   value=lib.get_string(
                                       'help:sprintNotifySub',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint forget`',
                                   value=lib.get_string(
                                       'help:sprintForgetSub',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.add_field(name='`sprint status`',
                                   value=lib.get_string(
                                       'help:sprintStatusSub',
                                       user.get_guild()),
                                   inline=True)
            sprint_embed.set_footer(
                text=lib.get_string('help:sprintFooter', user.get_guild()))

            return await context.send(embed=sprint_embed)

        elif command == 'wrote':
            wrote_embed = discord.Embed(title='Help with `wrote` command',
                                        color=3897943)
            wrote_embed.add_field(name='`wrote 500`',
                                  value=lib.get_string('help:wroteSub',
                                                       user.get_guild()),
                                  inline=True)
            wrote_embed.add_field(name='`wrote 500 sword`',
                                  value=lib.get_string('help:wroteprojectSub',
                                                       user.get_guild()),
                                  inline=True)

            await context.send(content=None, embed=wrote_embed)

        elif command == 'xp':
            xp_embed = discord.Embed(title='Help with `xp` command.',
                                     color=3897943)
            xp_embed.add_field(name='`xp`',
                               value=lib.get_string('help:xpSub',
                                                    user.get_guild()),
                               inline=True)
            xp_embed.add_field(name='`xp top`',
                               value=lib.get_string('help:xpTopSub',
                                                    user.get_guild()),
                               inline=True)

            return await context.send(embed=xp_embed)

        elif command == 'remind':
            xp_embed = discord.Embed(title='Help with `remind` command.',
                                     color=3897943)
            xp_embed.add_field(name='`remind list`',
                               value=lib.get_string('help:remind:list',
                                                    user.get_guild()),
                               inline=True)
            xp_embed.add_field(name='`remind delete`',
                               value=lib.get_string('help:remind:delete',
                                                    user.get_guild()),
                               inline=True)
            xp_embed.add_field(
                name='`remind in 5 send hello everyone to #channel-name`',
                value=lib.get_string('help:remind:set:in', user.get_guild()),
                inline=True)
            xp_embed.add_field(
                name='`remind at 12:00 send hello everyone to #channel-name`',
                value=lib.get_string('help:remind:set:at', user.get_guild()),
                inline=True)
            xp_embed.add_field(
                name=
                '`remind every hour from 16:05 send hello everyone to #channel-name`',
                value=lib.get_string('help:remind:set:every:hour',
                                     user.get_guild()),
                inline=True)
            xp_embed.add_field(
                name=
                '`remind every day at 16:05 send hello everyone to #channel-name`',
                value=lib.get_string('help:remind:set:every:day',
                                     user.get_guild()),
                inline=True)
            xp_embed.add_field(
                name=
                '`remind every week at 16:05 send hello everyone to #channel-name`',
                value=lib.get_string('help:remind:set:every:week',
                                     user.get_guild()),
                inline=True)
            return await context.send(embed=xp_embed)
예제 #16
0
 def test_double_part(self):
     expected = {
         "twenty-one": 21,
         "twenty-two": 22,
         "twenty-three": 23,
         "twenty-four": 24,
         "twenty-five": 25,
         "twenty-six": 26,
         "twenty-seven": 27,
         "twenty-eight": 28,
         "twenty-nine": 29,
         "thirty-one": 31,
         "thirty-two": 32,
         "thirty-three": 33,
         "thirty-four": 34,
         "thirty-five": 35,
         "thirty-six": 36,
         "thirty-seven": 37,
         "thirty-eight": 38,
         "thirty-nine": 39,
         "forty-one": 41,
         "forty-two": 42,
         "forty-three": 43,
         "forty-four": 44,
         "forty-five": 45,
         "forty-six": 46,
         "forty-seven": 47,
         "forty-eight": 48,
         "forty-nine": 49,
         "fifty-one": 51,
         "fifty-two": 52,
         "fifty-three": 53,
         "fifty-four": 54,
         "fifty-five": 55,
         "fifty-six": 56,
         "fifty-seven": 57,
         "fifty-eight": 58,
         "fifty-nine": 59,
         "sixty-one": 61,
         "sixty-two": 62,
         "sixty-three": 63,
         "sixty-four": 64,
         "sixty-five": 65,
         "sixty-six": 66,
         "sixty-seven": 67,
         "sixty-eight": 68,
         "sixty-nine": 69,
         "seventy-one": 71,
         "seventy-two": 72,
         "seventy-three": 73,
         "seventy-four": 74,
         "seventy-five": 75,
         "seventy-six": 76,
         "seventy-seven": 77,
         "seventy-eight": 78,
         "seventy-nine": 79,
         "eighty-one": 81,
         "eighty-two": 82,
         "eighty-three": 83,
         "eighty-four": 84,
         "eighty-five": 85,
         "eighty-six": 86,
         "eighty-seven": 87,
         "eighty-eight": 88,
         "eighty-nine": 89,
         "ninety-one": 91,
         "ninety-two": 92,
         "ninety-three": 93,
         "ninety-four": 94,
         "ninety-five": 95,
         "ninety-six": 96,
         "ninety-seven": 97,
         "ninety-eight": 98,
         "ninety-nine": 99,
     }
     for test in expected:
         self.assertEqual(get(test), '"' + test + '" parses to ' + str(expected[test]))
예제 #17
0
def scrapeBookList(cols, bookList):
    url = "https://www.studystore.nl/en/boekenlijst/"

    name = cols[0]
    period = cols[2].split("-")[0].strip()
    number = bookList["SchoolListNumber"]

    cols[6] = bookList["Name"]

    url = url + name + "/" + period + "/" + number + "/" + bookList["Url"]

    print("Requesting book list: " + bookList["Url"])

    #scrape books
    html = lib.get(url, soup=True)
    if (html):
        courses = html.find_all("div", {"class": "booklist__course"})
        for course in courses:
            course_name = course.find("h4",
                                      {"class": "booklist__course-title"})
            if (course_name):
                cols[7] = course_name.text

            books = course.find_all("div", {"class": "itemlist__row"})
            for book in books:
                book_title = book.find("p",
                                       {"class": "booklist__product-title"})
                if (book_title):
                    book_name = book_title.text.strip()
                    cols[8] = book_name

                warning = book.find("div",
                                    {"class": "booklist__product-warning"})
                if (warning):
                    ps = warning.find_all("p")
                    for p in ps:
                        if (p.text.lower() == "compulsory"):
                            cols[9] = "Yes"

                authors = book.find("div", {"class": "booklist__product-info"})
                authors = authors.find("div",
                                       {"class": "booklist__product-authors"})
                if (authors):
                    cols[10] = authors.text.strip()

                subinfo = book.find("div", {"class": "subinfo-sm"})
                if (subinfo):
                    subinfo_all = subinfo.findChildren()
                    for _subinfo in subinfo_all:
                        if ("isbn" in _subinfo.text.lower()):
                            cols[11] = _subinfo.text.lower().split(
                                "isbn:")[1].strip()
                        if ("edition" in _subinfo.text.lower()):
                            cols[12] = _subinfo.text.lower().split(
                                "edition:")[1].strip()

                price = ""
                _price = book.find("div",
                                   {"class": "product-list__price_from"})
                if (_price):
                    price = _price.text
                discount = price
                _discount = book.find("div",
                                      {"class": "product-list__price_to"})
                if (_discount):
                    discount = _discount.text
                cols[13] = price
                cols[14] = discount

                cols[16] = url
                writeRow(cols)

                cols[8] = empty_chr
                cols[9] = empty_chr
                cols[10] = empty_chr
                cols[11] = empty_chr
                cols[12] = empty_chr
                cols[13] = empty_chr
                cols[14] = empty_chr
                cols[15] = empty_chr
                cols[16] = empty_chr

    cols[6] = empty_chr
예제 #18
0
    async def run_info(self, context):
        """
        Get the event information embedded message
        :param context:
        :return:
        """
        user = User(context.message.author.id, context.guild.id, context)
        event = Event.get_by_guild(user.get_guild())
        config = lib.get('./settings.json')

        # Make sure there is an event
        if event is None:
            return await context.send(
                user.get_mention() + ', ' +
                lib.get_string('event:err:noexists', user.get_guild()))

        # Work out which timezone to use when displaying the start and end dates.
        start_date = lib.get_string('na', user.get_guild())
        end_date = lib.get_string('na', user.get_guild())
        user_timezone = user.get_setting('timezone')
        if not user_timezone:
            user_timezone = 'UTC'

        timezone = pytz.timezone(user_timezone)

        # Is it scheduled with start and end dates?
        if event.is_scheduled():
            start = datetime.fromtimestamp(event.get_start_time())
            end = datetime.fromtimestamp(event.get_end_time())
            start_date = start.astimezone(timezone).strftime(
                '%d-%m-%Y %H:%M:%S') + ' (' + user_timezone + ')'
            end_date = end.astimezone(timezone).strftime(
                '%d-%m-%Y %H:%M:%S') + ' (' + user_timezone + ')'

        # Get the running status
        if event.is_running():
            status = lib.get_string('event:started', user.get_guild())
        else:
            status = lib.get_string('event:notyetstarted', user.get_guild())

        # Get the number of users in the event and how many words they have written in it so far
        writers = len(event.get_users())
        words = event.get_total_wordcount()

        # Get the description of the event and add to the end of the status, or just display the status if the description is empty
        description = event.get_description()
        if description and len(description) > 0:
            description = status + '\n\n' + description
        else:
            description = status

        # Get the thumbnail image to use
        image = event.get_image()
        if not image or len(image) == 0:
            image = config.avatar

        # Build the embedded message.
        embed = discord.Embed(title=event.get_title(),
                              color=event.get_colour(),
                              description=description)
        embed.set_thumbnail(url=image)
        embed.add_field(name=lib.get_string('event:startdate',
                                            user.get_guild()),
                        value=start_date,
                        inline=False)
        embed.add_field(name=lib.get_string('event:enddate', user.get_guild()),
                        value=end_date,
                        inline=False)
        embed.add_field(name=lib.get_string('event:numwriters',
                                            user.get_guild()),
                        value=str(writers),
                        inline=True)
        embed.add_field(name=lib.get_string('event:numwords',
                                            user.get_guild()),
                        value=str(words),
                        inline=True)

        # Send the message
        return await context.send(embed=embed)
예제 #19
0
    async def get_leaderboard(self, limit=None):
        """
        Build the embedded leaderboard to display
        :return:
        """

        config = lib.get('./settings.json')
        users = self.get_users()

        # Build the embedded leaderboard message
        title = self.get_title() + ' - ' + lib.get_string(
            'event:leaderboard', self.get_guild())
        description = lib.get_string('event:leaderboard:desc',
                                     self.get_guild()).format(
                                         limit, self.get_title())
        footer = lib.get_string('event:leaderboard:footer',
                                self.get_guild()).format(limit)

        # If there is no limit, don't show the footer
        if limit is None:
            footer = None

        # If the event is finished, don't show the footer and adjust the description to take out 'so far'
        if self.is_ended():
            description = lib.get_string('event:leaderboard:desc:ended',
                                         self.get_guild()).format(
                                             self.get_title())
            footer = None

        image = self.get_image()
        if not image or len(image) == 0:
            image = config.avatar

        embed = discord.Embed(title=title,
                              color=self.get_colour(),
                              description=description)
        embed.set_thumbnail(url=image)
        if footer:
            embed.set_footer(text=footer, icon_url=config.avatar)

        # Get an array of all the user ids, so we can fetch them and make sure they still exist on the guild.
        user_ids = list(map(lambda row: row['user'], users))

        # Using those user_ids, look them all up and return a list of those which are still on the guild.
        if user_ids:
            members = await self.__guild.query_members(limit=100,
                                                       cache=False,
                                                       user_ids=user_ids)

            # Create a sub method to find a user in the members list by their id
            def find_member(id):
                for m in members:
                    if m.id == id:
                        return m
                return None

            # Loop through the users, filtering out any which are not on the guild and returning their name for display.
            position = 1

            for user in users:

                member = find_member(int(user['user']))
                if member is not None and position <= self.LEADERBOARD_LIMIT:

                    # Build the name and words variables to display in the list
                    name = str(position) + '. ' + member.display_name
                    words = str(user['words']) + ' ' + lib.get_string(
                        'words', self.get_guild())

                    # Embed this user result as a field
                    embed.add_field(name=name, value=words, inline=False)

                    # Increment position
                    position += 1

        return embed
예제 #20
0
def main():
    parser = argparse.ArgumentParser(
        description="Sync file repositories in parallel",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument('repositories', nargs='+',
                        help='file repository(ies) to sync')
    args = lib.add_common_params_and_parse(parser)

    repo_remote = []
    for r in args.repositories:
        repo = create_repo(lib.get_random_string())
        logging.debug("Created repository %s" % repo)
        remote = create_remote(lib.get_random_string(), r)
        logging.debug("Created remote %s" % remote)
        repo_remote.append((repo, remote))

    tasks = []
    for repo, remote in repo_remote:
        task = start_sync(repo, remote)
        logging.debug("Created sync task %s" % task)
        tasks.append(task)

    results = lib.wait_for_tasks(tasks)
    print(lib.tasks_table(results))
    print(lib.tasks_min_max_table(results))
    print("Sync tasks waiting time:", lib.tasks_waiting_time(results))
    print("Sync tasks service time:", lib.tasks_service_time(results))

    tasks = []
    for repo, remote in repo_remote:
        task = create_publication(repo)
        logging.debug("Created publication task %s" % task)
        tasks.append(task)

    results = lib.wait_for_tasks(tasks)
    print(lib.tasks_table(results))
    print(lib.tasks_min_max_table(results))
    print("Publication tasks waiting time:", lib.tasks_waiting_time(results))
    print("Publication tasks service time:", lib.tasks_service_time(results))

    publications = []
    for result in results:
        pub = result['created_resources'][0]
        publications.append(pub)

    tasks = []
    for pub in publications:
        task = create_distribution(lib.get_random_string(), lib.get_random_string(), pub)
        logging.debug("Created distribution task %s" % task)
        tasks.append(task)

    results = lib.wait_for_tasks(tasks)
    print(lib.tasks_table(results))
    print(lib.tasks_min_max_table(results))
    print("Distribution tasks waiting time:", lib.tasks_waiting_time(results))
    print("Distribution tasks service time:", lib.tasks_service_time(results))

    distributions = []
    dist_base_urls = []
    for result in results:
        distribution = result['created_resources'][0]
        distributions.append(distribution)
        dist_base_urls.append(lib.get(distribution)['base_url'])

    return 0
예제 #21
0
    def old_calibrations(self, pars, which='mn', calSlice=(None,None), N=1000, label='', **kwargs):

        sampleList = [c['sample'] for c in calibration_specs() if c['which']==which]
        prePre = pars['dirIncrement'] in [0,4,5]

        args = {
            'signal':pars['signal'],
            'sigPrefix':pars['sigPre'],
            'dirPrefix':"R%02d" % (pars['R0_'] + pars['dirIncrement']),
            'genDirPre':pars['genDirPre'],
            'prePre':prePre,
            'templateID':None,
            'sampleList': sampleList,
            'rebin':pars['rebin'],
            'no3D':pars['no3D']
            }
        alt_channels = dict( [ ((lep,part), inputs.channel_data(lep, part, **args))
                               for lep in ['el','mu'] for part in ['top','QCD']] )

        if 'xsfactor' in kwargs:
            alt_channels[('el','top')].samples['ttalt'].xs *= kwargs['xsfactor']
            alt_channels[('mu','top')].samples['ttalt'].xs *= kwargs['xsfactor']

        # get Ac_phi_ttalt and Ac_y_ttalt
        filePattern = 'data/stats_top_mu_%s.root'
        tag = 'ph_sn_jn_20'
        tfile = r.TFile.Open(filePattern%tag)
        h = lib.get(tfile,'genTopTanhDeltaAbsY_genTopDPtDPhi/'+ sampleList[0])
        Ac_y_ttalt = lib.asymmetry(h.ProjectionX())[0]
        Ac_phi_ttalt = lib.asymmetry(h.ProjectionY())[0]
        tfile.Close()

        model = self.central.model
        model.import_alt_model(alt_channels, pars['nobg'])
        wGen = model.w

        # bring xs_ttalt to the most consistant value possible
        wGen.arg('d_xs_ttalt').setVal((wGen.arg('expect_mu_tt').getVal() + wGen.arg('expect_el_tt').getVal()) /
                                      (wGen.arg('expect_mu_ttalt').getVal() + wGen.arg('expect_el_ttalt').getVal()) - 1)
        if not (-0.5 < wGen.arg('d_xs_ttalt').getVal() < 1.5):
            print 'ttalt xs invalid! Adjust calibration_specs!'
            exit()
        # not clear how to do the same for factor_*_qcd (equivalent bg representations)

        truth = {'Ac': Ac_y_ttalt if genNames['XL'][3:] in pars['signal'] else Ac_phi_ttalt}
        altItems = ['expect_%s_ttalt'%s for s in ['el','mu']]
        for item in (set(fit.modelItems()+altItems)-set()): truth[item] = wGen.arg(item).getVal()
        truth.update({'Ac_raw_el_model':model.Ac_raw('el','alt%smodel'%pars['nobg']),
                      'Ac_raw_mu_model':model.Ac_raw('mu','alt%smodel'%pars['nobg'])})

        mcstudy = r.RooMCStudy(wGen.pdf('alt%smodel'%pars['nobg']),
                               wGen.argSet(','.join(model.observables+['channel'])),
                               r.RooFit.Binned(True),
                               r.RooFit.Extended(True)
                           )
        mcstudy.generate(N,0,True)
        for i in range(*calSlice):
            alt = mcstudy.genData(i)
            pars['label'] = '%s_cal%s%03d'%(label,which,i)
            pars['quiet'] = True
            with open(self.outNameBase + pars['label'] + '.log', 'w') as log:
                pars['log']=log
                f = fit(altData=alt, **pars)
            f.ttreeWrite(self.outNameBase + pars['label'] + '.root', truth)
            if self.doVis: f.model.visualize(self.outNameBase + pars['label'] + '.pdf', nobg=pars['nobg'])
예제 #22
0
파일: inputs.py 프로젝트: betchart/statsTA
 def get(s,ps):
     return next(iter(filter(None, [lib.get(tfile,p+s) for p in ps])), None)
예제 #23
0
def update():
    """Update cache of project presets

    Calling this will initiate a number of requests to GitHub and it's API
    in order to update the in-memory cache of each publicly avaialble project
    for be.

    """

    log.info("Updating..")

    raw = "https://raw.githubusercontent.com/{repo}/master/{fname}"
    api = "https://api.github.com/repos/{repo}/{endpoint}"
    repo_link = "https://github.com/{repo}"
    gist_link = "https://gist.github.com/{repo}"

    endpoint = raw.format(repo="mottosso/be-presets",
                          fname="presets.json")
    presets_json = lib.get(endpoint).json()
    presets = list()
    for preset in presets_json.get("presets", []):
        try:
            user, repo = preset["repository"].split("/", 1)
        except ValueError as e:
            log.error("Incorrectly formatted repository "
                      "name: %s" % preset["repository"])
            log.error(str(e))
            continue

        repo = preset["repository"]
        package, source = lib.package(repo)

        if not package:
            log.error("package.json not found in %s" % repo)
            continue

        thumbnail = package.get("thumbnail")
        if thumbnail:
            thumbnail = raw.format(repo=repo,
                                   fname=thumbnail)
        else:
            thumbnail = "static/img/default_thumbnail.png"
        print thumbnail

        stargazers_url = api.format(repo=repo,
                                    endpoint="stargazers")
        stargazers = len(lib.get(stargazers_url).json())

        label = (package.get("label") or
                 preset["name"].replace("-", " ").title())
        description = package.get("description")

        if not description:
            description = "No description"
        elif len(description) > 70:
            description = description[:67] + "..."

        link = gist_link if source == "gist" else repo_link
        link = package.get("link") or link.format(repo=repo)

        presets.append({
            "name": preset["name"],
            "label": label,
            "repository": preset["repository"],
            "likes": 10,
            "link": link,
            "description": description,
            "thumbnail": thumbnail,
            "likes": stargazers
        })

    self.cache[:] = presets
    log.info("Done")